
python 获取url的数据
我想用Python程序访问一个网页,并获取该网页的HTML代码,应该用什么方法?
用Python的requests库获取网页数据
Python的requests库提供了简单的方式请求网页。你可以通过requests.get()函数传入目标URL,然后使用response.text属性获取网页的HTML内容。例如:
import requests
response = requests.get('http://example.com')
html_content = response.text
一些API接口返回的是JSON格式数据,怎样用Python请求URL并解析JSON格式的数据?
使用requests库请求API并解析JSON
Python中requests库可以方便地请求API接口,调用response.json()方法即可将返回的JSON字符串转换成Python的字典或列表。例如:
import requests
response = requests.get('http://api.example.com/data')
data = response.json()
在使用Python从URL获取数据时,有时会遇到连接超时或状态码不是200的情况,应该如何处理和调试?
检查状态码并捕获异常进行调试
请求网页时,最好先检查response.status_code是否为200,确保请求成功。还应使用try-except捕获requests.exceptions.RequestException异常,方便排查网络问题。此外,可以设置超时参数提高程序稳定性。示例代码:
import requests
try:
response = requests.get('http://example.com', timeout=5)
response.raise_for_status() # 抛出异常如果响应不是200
data = response.text
except requests.exceptions.RequestException as e:
print('请求出现错误:', e)