python 爬虫的一些设置参数

python 爬虫

设置headers

1
2
3
4
5
6
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
}

zh-CN: 最高优先级,客户端最希望收到简体中文的内容。

zh;q=0.8: 如果服务器不能提供 zh-CN,那退而求其次接受普通中文,优先级稍低。

en-US;q=0.6: 如果没有中文版本,接受美式英文。

en;q=0.4: 最低优先级,接受其他形式的英文。

作用: 设置 HTTP 请求头,比如伪装成浏览器、添加认证信息等

设置proxies

1
2
3
4
5
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
r = requests.get("http://httpbin.org/ip", proxies=proxies)

设置请求代理服务器

设置params

1
2
3
4
5
params = {
"wd": "python",
}
response = requests.get(url, headers=headers, params=params)
url : https://www.baidu.com/s?wd=python

作用: 传递 URL 查询参数(即 ?key=value 形式)

设置cookies

1
2
3
4
cookies = {
"cookie": "name=germey",
}
response = requests.get(url, headers=headers, cookies=cookies)

作用: 传递 cookies,即 HTTP 请求中的 cookie 信息

设置auth

1
2
3
4
from requests.auth import HTTPBasicAuth
HTTPBasicAuth = requests.auth.HTTPBasicAuth('user', 'pass')
r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=HTTPBasicAuth)
print(r.status_code)

作用: 提供 HTTP 基本认证

设置allow_redirects

1
response = requests.get(url, allow_redirects=False)

是否允许重定向(默认 True)

设置verify

1
2
r = requests.get('https://expired.badssl.com', verify=False)
print(r.status_code)

是否验证 SSL 证书(默认 True)