在写python爬虫的时候,为防止对方发现爬虫IP和封停IP,那写爬虫的时候,就要用python去抓取一些代理IP,然后用这些代理IP不停地轮徇地爬取对方数据。在现实使用中,最好要隔段时间就去爬一次代理IP,并添加到代理IP库中,同时把不能使用的IP踢出IP库,每次爬求数据时,从代理IP库中随机(random .choice)获取一个IP。
脚本主要使用到requests模块和Beautiful Soup(bs4 )模块
以下是爬取代理IP的简易脚本:
- import re
- from random import choice
- import requests
- import bs4
- url = "http://www.xicidaili.com/nn"
- headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
- "Accept-Encoding":"gzip",
- "Accept-Language":"zh-CN,zh;q=0.8",
- "Referer":"http://www.xicidaili.com/",
- "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
- }
- r = requests.get(url,headers=headers)
- soup = bs4.BeautifulSoup(r.text, 'html.parser')
- data = soup.table.find_all("td",limit=40) # limit是获取td的个数,这里可以指定获取多少个IP
- ip_compile= re.compile(r'<td>(\d+\.\d+\.\d+\.\d+)</td>')
- port_compile = re.compile(r'<td>(\d+)</td>')
- ip = re.findall(ip_compile,str(data))
- port = re.findall(port_compile,str(data))
- ips = [":".join(i) for i in zip(ip,port)]
- print u"代理IP列表:{ip_list}".format(ip_list=ips)
- print u"随机在代理IP列表中选一个IP:{ip}".format(ip=choice(ips))
脚本中使用requests模块去请求url,爬取数据
使用re模块写正则匹配IP和端口,这IP和端口,都在HTML td元素中:
re.compile(r'<td>(\d+\.\d+\.\d+\.\d+)</td>')
re.compile(r'<td>(\d+)</td>')
用 bs4 模块去解析HTML数据,拿我们要指定的元素节点中的数据
最后在使用IP时,可以用random .choice随机返回一个IP
re匹配表达式,还要看对方网站的HTML元素是怎么写的,要根据具体情况具体判断
以下是python爬虫脚本中相关模块的教程文档:
bs4(Beautiful Soup) 模块教程文档:http://beautifulsoup.readthedocs.io/zh_CN/latest/
requests模块教程文档:http://cn.python-requests.org/zh_CN/latest/
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏