python request get
1 import requests
2 from urllib import parse
3
4 # 返回response
5 resp = requests.get("https://www.baidu.com")
6
7 # 查看状态码
8 print(resp.status_code)
9
10
11 # 查看响应编码 ISO-8859-1
12 print(resp.encoding)
13
14
15 # response.text返回文本内容
16 print(resp.text)
17
18 # response.content返回的是二进制内容,decode,默认是utf-8方式解码
19 print(resp.content.decode())
20
21 # 查看默认的headers
22 print(resp.request.headers)
23
24 # 设置headers
25 headers = {
26 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
27 }
28
29 # 设置参数
30 params = {"wd": "淘宝"}
31
32 # 查询
33 resp = requests.get("https://www.baidu.com/s", headers=headers, params=params)
34
35 # 查看请求的url, 请求的url与响应的url有时由于重定向的原因会不一致
36 url = resp.request.url
37
38 # 对url进行解码 https://www.baidu.com/s?wd=淘宝
39 print(parse.unquote(url))
40
41 # print(resp.content.decode())
42
43 # print(resp.request.headers)
44
45
46 # 拼接参数,也可以用 %s的方式
47 resp = requests.get("https://www.baidu.com/s?{}".format("wd=天猫"), headers=headers)
48
49 url = resp.request.url
50 # https://www.baidu.com/s?wd=天猫
51 print(parse.unquote(url))