python爬虫从入门到放弃(六)学习IP相关知识
1、学习什么是IP,为什么会出现IP被封,如何应对IP被封的问题。
因为网站都有反爬虫措施,所以很容易被封IP。
防止被封的办法有方法集
伪造User-Agent
在请求头中把User-Agent设置成浏览器中的User-Agent,来伪造浏览器访问。比如:
headers = {‘User-Agent’:‘Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36’}
resp = requests.get(url,headers = headers)
还可以先收集多种浏览器的User-Agent,每次发起请求时随机从中选一个使用,可以进一步提高安全性:
In [7]: import requests,random
In [8]: user_agents = [‘Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1’,‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50’,‘Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11’]
In [9]: def get_html(url):
…: headers = {‘User-Agent’:random.choice(user_agents)}
…: resp = requests.get(url,headers = headers)
…: return resp.text
把上面随机选择一个User-Agent的代码封装成一个函数:
import random
def get_headers():
‘’’
随机获取一个headers
‘’’
user_agents = [‘Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1’,‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50’,‘Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11’]
headers = {‘User-Agent’:random.choice(user_agents)}
return headers
注:一些常见浏览器的User-Agent可参见:https://www.geek-share.com/detail/2730898701.html
在每次重复爬取之间设置一个随机时间间隔
比如:
time.sleep(random.randint(0,3)) # 暂停0~3秒的整数秒,时间区间:[0,3]
或:
time.sleep(random.random()) # 暂停0~1秒,时间区间:[0,1)
伪造cookies
若从浏览器中可以正常访问一个页面,则可以将浏览器中的cookies复制过来使用,比如:
cookies = dict(uuid=‘b18f0e70-8705-470d-bc4b-09a8da617e15’,UM_distinctid=‘15d188be71d50-013c49b12ec14a-3f73035d-100200-15d188be71ffd’)
resp = requests.get(url,cookies = cookies)
把浏览器的cookies字符串转成字典
def cookies2dict(cookies):
items = cookies.split(’;’)
d = {}
for item in items:
kv = item.split(’=’,1)
k = kv[0]
v = kv[1]
d[k] = v
return d
注:用浏览器cookies发起请求后,如果请求频率过于频繁仍会被封IP,这时可以在浏览器上进行相应的手工验证(比如点击验证图片等),然后就可以继续正常使用该cookies发起请求。
使用代理
可以换着用多个代理IP来进行访问,防止同一个IP发起过多请求而被封IP,比如:
proxies = {‘http’:‘http://10.10.10.10:8765’,‘https’:‘https://10.10.10.10:8765’}
resp = requests.get(url,proxies = proxies)
注:免费的代理IP可以在这个网站上获取:http://www.xicidaili.com/nn/
2、抓取西刺代理,并构建自己的代理池
a|先设置一个代理以免被封
b| 抓取西刺代理,并构建自己的代理池。
西刺代理网址:https://www.xicidaili.com/nn/
首先根据BeautifulSoup解析出ip所在标签,并将其提取,其次依次对所提取标签进行验证是否为有效ip,最后将有效ip写入文件
整体代码如下
# -*- coding:utf-8 -*- import requests, json, re, random,time from bs4 import BeautifulSoup class getUrl(object): """docstring for getUrl""" def __init__(self): self.headers={ "Connection": "keep-alive", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch"< 4000 /span>, "Accept-Language": "zh-CN,zh;q=0.8" }; def run(self): # 以第一页为例 url = 'http://www.xicidaili.com/nn' req = requests.get(url,headers=self.headers) html = req.text soup = BeautifulSoup(html, 'lxml') ip_list = soup.find(id='ip_list').find_all('tr') for i in range(1, len(ip_list)): ip_info = ip_list[i] tds = ip_info.find_all('td') ip = tds[1].text + ':' + tds[2].text # 验证ip是否可用 if self.verify_IP(ip): #可用ip写入文件 dir_file = open("ip_records.txt",'a', encoding="utf-8") dir_file.write(ip+"\n") dir_file.close() time.sleep(5) def verify_IP(self,ip): proxies = {"http": ip} url = "http://www.baidu.com/" try: req = requests.get(url, headers=self.headers,proxies=proxies, timeout=3) if req.status_code == 200: return True else: return False except requests.RequestException as e: print("验证代理IP" + ip + "时发生如下错误 :") print(e) return False if __name__ == '__main__': geturl = getUrl() geturl.run()
- # Python 学习从入门到放弃(四)--类和模块的基础知识
- Python基础学习-爬虫入门知识
- Python 爬虫学习 —— Scrapy 入门知识学习
- Python 学习入门(6)—— 网页爬虫
- python小白入门学习笔记-爬虫入门
- python3 [入门基础实战] 爬虫入门之智联招聘的学习(一)
- Python 爬虫如何入门学习?
- 『python工作』爬虫相关知识、概念
- python 爬虫 学习笔记(一)Scrapy框架入门
- python爬虫入门(1) 基础知识 ; 正则表达式 Re 模块
- python python 入门学习之网页数据爬虫cnbeta文章保存
- 【Python爬虫】入门知识
- Python爬虫入门学习例子之煎蛋网(福利哦)
- Python爬虫学习笔记(2):多线程入门
- Python 爬虫入门—— IP代理使用
- python爬虫入门(二)——爬取代理IP
- Python爬虫从入门到放弃(十三)之 Scrapy框架的命令行详解
- python爬虫从入门到放弃(四)之 Requests库的基本使用
- 【Python爬虫学习笔记(1)】urllib2库相关知识点总结
- Python解析json文件相关知识学习