简单的反反爬虫技巧(1)
一,更换请求头。
-
1,当我们使用requests库获取网页时,如下面:
import requests url = r"https://www.plmm.com.cn/chemo/" resp = requests.get(url) print(resp.request.headers)
-
2,就会发现输出为:
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
-
3,user-agent属性值为python-requests,在很多网站爬取的过程中,会被拦截。
-
4,我们最简单的办法就是直接使用浏览器的检查功能粘贴浏览器中的请求头。如下:
import requests url = r"https://www.plmm.com.cn/chemo/" headers = { "User-Agent": r"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.85 Safari/537.36 Edg/80.0.361.47" } resp = requests.get(url, headers=headers) print(resp.request.headers)
即可成功解决问题
-
注意:这个方法在一些场合会出现请求失败的方法。
-
5,另外一种方法就是使用python库,来很方便的切换user-agent:fake-useragent,使用pip安装后,即可使用
import requests from fake_useragent import UserAgent url = r"https://www.plmm.com.cn/chemo/" ua = UserAgent() headers = { "Us" } headers = { "User-Agent": ua.random } resp = requests.get(url, headers=headers) print(resp.request.headers)
生成的请求头为:
{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
即可解决大部分问题。
这个生成不稳定,有时候会报错
-
6, 可以使用faker这个模块
from faker import Factory
# 生成不同的user-agent
fc = Factory.create()
for i in range(10):
print(fc.user_agent())
- 生成很稳定
二, 修改爬虫的间隔时间
-
1,当过快或者使用相同的时间间隔爬取网页时,容易被封i
-
2,使用随机的时间间隔来请求网站,来生成0-3秒之间的随机间隔时间
import time import random st = random.randint(0,2) + random.random() print(st)