Python之免费代理ip的抓取与使用
- 使用爬虫不可避免的就会遇到网站的各种封ip操作,因此就需要我们找寻代理,通过代理进行操作,屏蔽自己真实ip。
- 本文直接从网站中抓取代理ip地址,进行测试,并将测试的结果直接输出到MongoDB中,最后可实现去重操作
- 这里测试ip应该改成多线程才合适,但是目前我还不会,所以先这么着了,测试慢了点
- 核心字段在于
html = requests.get(url=url, headers=headers, proxies=proxy_ip)
,request中proxies字段的使用。
测试截图如下:
import requests
import pymongo
from lxml.html import etree
class SelfIpProxy():
def __init__(self):
self.depth = 1
self.timeout = 10
self.collection = pymongo.MongoClient()['Proxies']['free2']
self.url = {
'http':"http://19ncc.medmeeting.org/cn",'https':"https://www.baidu.com"}
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'Referer': 'https://www.xicidaili.com/nn/2'}
def get_ip(self):
urls = [
'https://www.xicidaili.com/nn/{}'.format(i) for i in range(1, self.depth + 1)]
for url in urls:
html = requests.get(url, headers=self.headers, timeout=30)
html.encoding = 'utf-8'
e_html = etree.HTML(html.text)
ips = e_html.xpath('//table[@id="ip_list"]/tr/td[2]/text()')
ports = e_html.xpath('//table[@id="ip_list"]/tr/td[3]/text()')
modes = e_html.xpath('//table[@id="ip_list"]/tr/td[6]/text()')
for ip, port, mode in zip(ips, ports, modes):
item = dict()
item