【爬虫学习6】爬虫自动获取并使用代理ip

来源:互联网 发布:app模型制作软件 编辑:程序博客网 时间:2024/05/24 06:27

当同一ip短时间内多次链接同一网站,很可能导致ip被封,所以需要利用代理ip防止封禁。
代理ip可以通过百度很容易的获取 比如 西刺代理
但是,很明显我们用爬虫的人,不是会一个个自己复制粘贴的人,所以自然想到用爬虫解决问题。
-本文不区分url和ip,为简化 都叫成ip
-文中有个特别注意一定要看
-本文全部代码见于我的Git

主要思路

1.从代理网站爬取IP地址及端口号并存储
2.验证ip能否使用
3.格式化ip地址
4.在requests中使用代理ip爬网站

具体实现

1.爬取代理IP

这一步很简单就直接上代码了

url = 'http://www.xicidaili.com/wt'def get_ip_list(url, headers):    """ 从代理网站上获取代理"""    ip_list = []    page = requests.get(url, headers=headers)    soup = BeautifulSoup(page.text, 'lxml')    ul_list = soup.find_all('tr', limit=20)    print(len(ul_list))    for i in range(2, len(ul_list)):        line = ul_list[i].find_all('td')        ip = line[1].text        port = line[2].text        address = ip + ':' + port        ip_list.append(address)    return ip_list

最终获得的是是这样的ip:port列表
这里写图片描述

2.验证ip可用

验证可用有两种思路:
- 在格式化好的用代理IP访问指定网站,如果返回状态为200,表示这个代理是可以使用的
- 在ip_list基础上使用telnet来验证

直接访问式验证

import requests #假设此时有一已经格式化好的ip代理地址proxiesproxies = {    http: 'http://114.99.7.122:8752'    https: 'https://114.99.7.122:8752'}headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063'}url = 'http://www.whatismyip.com.tw/'try:    page = requests.get(url, headers=headers, proxies=proxies)    except:        print('失败')    else:        print('成功')

这个方法很容易想到,但是受限于代理的延时,很慢,于是有了下面一个快一点的使用telnet来验证
方法:

#这里假设有ip_list中某一iphd, port = ip.split(':')try:    telnetlib.Telnet(hd, port=port, timeout=20)except:    print '失败'else:    print '成功'

3.格式化

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

import requestsrequests.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
当然为了省事,我们都加上,反正会验证能不能用,这样有更好的通用性。


具体格式化代码为:

def get_proxy(aip):    """构建格式化的单个proxies"""    proxy_ip = 'http://' + aip    proxy_ips = 'https://' + aip    proxy = {'https': proxy_ips, 'http': proxy_ip}    return proxy

4.使用代理建立爬虫

由于本身就是为了学习,所以建立爬虫爬取的是显示ip的网站http://www.whatismyip.com.tw/
这个网站会显示你的ip地址,从而可以很直观确认我们的代理是否成功了
代码是很简单的爬虫就直接上代码了:

def print_ip(proxies):    """利用http://www.whatismyip.com.tw/显示访问的ip"""    cookies = {        'sc_is_visitor_unique': 'rx6392240.1508897278.298AFF0AE2624F7BC72BADF517B67AEE.2.2.2.2.2.2.1.1.1',    }    headers = {        'Accept-Encoding': 'gzip, deflate',        'Accept-Language': 'zh-CN,zh;q=0.8',        'Upgrade-Insecure-Requests': '1',        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',        'Cache-Control': 'max-age=0',        'Connection': 'keep-alive',    }       url = 'http://www.whatismyip.com.tw/'    try:        page = requests.get(url, headers=headers, proxies=proxies)    except:        print(str(proxies) + 'is wrong')    else:        soup = BeautifulSoup(page.text, 'lxml')        my_ip = soup.find('b').text        print('成功连接' + my_ip)

可以看到这里用的是第一种方式确认ip的可用

如果运行成功有如下显示:
这里写图片描述

原创粉丝点击