随机生成浏览器信息
form fake_useragent import UserAgent
ua = UserAgent()
ua.random #随机生成浏览器信息
ua.Charom #指定谷歌头
request
import requests
import requests
#POST请求和GET请求并没有严格区分,对于GET请求我们也可以通过POST传递参数
#当然它也要delete(),put()方法
params = {
"start":"0",
"limit":'2'
}
r = requests.get(url,params,verify = False) #verify = False忽略ssl认证
response = requests.post(url,params,verify = False)
print(response .json()) #json数据可直接转换
response.encoding = 'gbk'
print(response.cookies)
print(response.text) #经过解码的,字符串式响应,但是解码不一定正确
print(response.content) #字节型响应
get请求可以下载图片,直接
ico = requests.get(url)
with open('./github.ico', mode='bw+') as fp:
fp.write(ico.content)
下载推荐使用
from urllib.request import urlretrieve
urlretrieve('https://github.com/favicon.ico', filename='github2.ico')
获取cookies
resp = requests.get('https://httpbin.org/cookies')
设置cookie
resp = requests.get('https://httpbin.org/cookies/set/name/zhangsan')
print(resp.json()) #输出cookies
在requests中使用session来维持会话
session = requests.Session()
resp = session.get('https://httpbin.org/cookies/set/name/zhangsan')
resp = session.get('https://httpbin.org/cookies')
print(resp.json())
在requests中使用代理
proxies = {
'http': '125.123.127.253:9999',
'https': '60.167.159.236:808'
}
resp = requests.get('https://www.baidu.com', proxies=proxies)
print(resp.text)