python中request
时间: 2023-11-22 13:39:49 浏览: 133
Python中的requests库是一个常用的HTTP库,用于发送HTTP请求和处理响应。根据提供的引用内容,有几种常见的使用方法可以使用:
1. 使用requests库发送GET请求,并打印响应内容。可以通过设置`url`和`headers`参数来指定目标网址和请求头。例如:
```python
import requests
url = "https://www.baidu.com/s?wd=python"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
print(response.text)
```
2. 使用requests库发送带参数的GET请求,并打印响应内容。可以通过设置`url`、`headers`和`params`参数来指定目标网址、请求头和请求参数字典。例如:
```python
import requests
url = "https://www.baidu.com/s?"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
kw = {'wd': 'python'}
response = requests.get(url, headers=headers, params=kw)
print(response.text)
```
3. 使用requests库发送带超时设置的GET请求。可以通过设置`timeout`参数来指定超时时间,以避免长时间等待。例如:
```python
import requests
url = "https://www.baidu.com/"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
try:
response = requests.get(url, headers=headers, timeout=5)
except:
for i in range(4):
response = requests.get(url, headers=headers, timeout=20)
if response.status_code == 200:
break
html_str = response.text
```
4. 使用requests库发送GET请求,并打印响应内容。可以通过设置`url`和`headers`参数来指定目标网址和请求头。例如:
```python
import requests
url = "https://www.taobao.com/"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
print(response.text)
```
阅读全文