python爬虫设置代理ip池——方法(一)

在使用python爬虫的时候,经常会遇见所要爬取的网站采取了反爬取技术,高强度、高效率地爬取网页信息常常会给网站服务器带来巨大压力,所以同一个IP反复爬取同一个网页,就很可能被封,那如何解决呢?使用代理ip,设置代理ip池。

以下介绍的免费获取代理ip池的方法:

优点:

1.免费

缺点:

1.代理ip稳定性差需要经常更换

2.爬取后ip存在很多不可用ip需要定期筛选

小建议:

该方法比较适合学习使用,如果做项目研究的话建议参考本人博客《python爬虫设置代理ip池——方法(二)》,购买稳定的代理ip。

一.主要思路

1.从代理ip网站爬取IP地址及端口号并储存

2.验证ip是否能用

3.格式化ip地址

4.在requests中使用代理ip爬取网站

二. 写在前面

在Requests中使用代理爬取的格式是

import requests
requests.get(url, headers=headers,proxies=proxies)

其中proxies是一个字典其格式为:
对每个ip都有

proxies = {
http: 'http://114.99.7.122:8752'
https: 'https://114.99.7.122:8752'
}

注意:
对于http和https两个元素,这里的http和https
代表的不是代理网站上在ip后面接的类型
代表的是requests访问的网站的传输类型是http还是https

你爬的网站是http类型的你就用http,如果是https类型的你就用https,在代理网站上爬的时候也要分别爬http或https的ip

三.代码

1.配置环境,导入包

# IP地址取自国内髙匿代理IP网站:http://www.xicidaili.com/nn/
# 仅仅爬取首页IP地址就足够一般使用
 
from bs4 import BeautifulSoup
import requests
import random
 
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}

2.获取网页内容函数

def getHTMLText(url,proxies):
    try:
        r = requests.get(url,proxies=proxies)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
    except:
        return 0
    else:
        return r.text

3.从代理ip网站获取代理ip列表函数,并检测可用性,返回ip列表

def get_ip_list(url):
    web_data = requests.get(url,headers)
    soup = BeautifulSoup(web_data.text, 'html')
    ips = soup.find_all('tr')
    ip_list = []
    for i in range(1, len(ips)):
        ip_info = ips[i]
        tds = ip_info.find_all('td')
        ip_list.append(tds[1].text + ':' + tds[2].text)
#检测ip可用性,移除不可用ip:(这里其实总会出问题,你移除的ip可能只是暂时不能用,剩下的ip使用一次后可能之后也未必能用)
    for ip in ip_list:
        try:
          proxy_host = "https://" + ip
          proxy_temp = {"https": proxy_host}
          res = urllib.urlopen(url, proxies=proxy_temp).read()
        except Exception as e:
          ip_list.remove(ip)
          continue
    return ip_list

4.从ip池中随机获取ip列表

def get_random_ip(ip_list):
    proxy_list = []
    for ip in ip_list:
        proxy_list.append('http://' + ip)
    proxy_ip = random.choice(proxy_list)
    proxies = {'http': proxy_ip}
    return proxies

5.调用代理

if __name__ == '__main__':
    url = 'http://www.xicidaili.com/nn/'
    ip_list = get_ip_list(url)
    proxies = get_random_ip(ip_list)
    print(proxies)

引用网址:

https://blog.csdn.net/weixin_40372371/article/details/80154707

猜你喜欢

转载自blog.csdn.net/xingxingmingyue/article/details/89514610