import requestsheaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win6
4; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/5
37.36"}url = ’https://www.baidu.com/s?wd=python’response = requests.get(url,
headers=headers)
2.2.2 通过 params 携带参数字典
1.构建请求参数字典
2.向接口发送请求的时候带上参数字典,参数字典设置给 params
import requestsheaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win6
4; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/5
37.36"}#
这 是 目 标
url# url = ’https://www.baidu.com/s?wd=python’#
最 后 有 没 有
问 号 结 果 都 一 样
url = ’https://www.baidu.com/s?’#
请 求 参 数 是 一 个字 典
即
wd=pythonkw = {’wd’: ’python’}#
带 上 请 求 参 数 发起 请求 , 获 取 响 应
response = requests.get(url, headers=headers, params=kw)print(response.cont
ent)
通过运行结果可以判断,请求的链接自动被构造成了:
http://httpbin.org/get?key2=value2&key1=value1 。
另外,网页的返回类型实际上是 str 类型,但是它很特殊,是 JSON 格
式的。所以,如果想直接解析返回结果,得到一个字典格式的话,可以
直接调用 json() 方法。示例如下:
import requestsr = requests.get("http://httpbin.org/get")print( type(r.text)
)print(r.json())print( type(r. json()))
< class ’str’ >
{ ’args’ : {}, ’headers’ : { ’Accept’ : ’*/*’ , ’Accept-Encoding’ : ’gzip,
deflate’ , ’Host’’httpbin.org’ , ’User-Agent’ : ’python-requests/2.24.0’ , ’X-Amzn
-Trace-Id’ : ’Root=1-5fb5b3f9-13f7c2192936ec541bf97841’ }, ’origin’ : ’36.4
4.144.134’ , ’url’ : ’http://httpbin.org/get’ }
评论0