在Python中,发送GET请求通常使用`requests`库,以下是使用`requests`库发送GET请求的基本步骤和示例代码:
1. 导入`requests`库:
python
import requests
2. 定义请求的URL:
python
url = 'http://example.com/api/data'
3. 发送GET请求,可以传递参数,参数以字典形式传递:
python
params = {
'param1': 'value1',
'param2': 'value2'
}
response = requests.get(url, params=params)
4. 处理响应,获取状态码、文本内容等:
python
status_code = response.status_code
text = response.text
5. 打印响应内容:
python
print(text)
完整的示例代码如下:
python
import requests
定义请求的URL和参数
url = 'http://example.com/api/data'
params = {
'param1': 'value1',
'param2': 'value2'
}
发送GET请求
response = requests.get(url, params=params)
处理响应
status_code = response.status_code
text = response.text
打印响应内容
print(text)
如果需要使用`urllib`库发送GET请求,代码如下:
python
import urllib.request
定义请求的URL
url = 'http://example.com/api/data'
发送GET请求
response = urllib.request.urlopen(url)
读取响应内容
html = response.read()
打印响应内容
print(html.decode('utf-8'))
请根据实际需要选择使用`requests`或`urllib`库发送GET请求
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/63407.html