import requests url = "https://www.cdairport.com/dynamic3.aspx?t=8&inout=D&date=0&etime=23:59&" html = requests.get(url) print(html)怎么修改
时间: 2024-10-23 18:19:31 浏览: 39
您提供的代码片段是使用requests库发送GET请求到指定URL,并打印返回的HTML内容。如果需要对这个代码做修改,可以按照以下步骤:
1. **添加异常处理**:在`requests.get()`前加上try-except块,以便捕获可能出现的网络错误或其他异常。
```python
import requests
url = "https://www.cdairport.com/dynamic3.aspx?t=8&inout=D&date=0&etime=23:59&"
try:
html = requests.get(url)
# 添加状态码检查,如果不是200则捕获错误
if html.status_code != 200:
print(f"请求失败,状态码: {html.status_code}")
else:
print(html.text)
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
```
2. **解析响应内容**:如果你只想获取数据而不是整个HTML,可以查看响应的内容类型并根据情况解析。比如,如果是JSON,可以用`json()`函数解析;如果是XML,可以使用`xml.etree.ElementTree`模块。
```python
import requests
from bs4 import BeautifulSoup # 如果是HTML,需要安装BeautifulSoup库
try:
response = requests.get(url)
if response.status_code == 200:
if 'application/json' in response.headers['Content-Type']:
data = response.json()
print(data)
elif 'text/html' in response.headers['Content-Type']:
soup = BeautifulSoup(response.text, 'lxml')
# 解析HTML内容,提取你需要的信息
content = soup.find('your_tag') # 替换 'your_tag' 为实际标签名
print(content.text)
else:
# ...处理状态码...
except requests.exceptions.RequestException as e:
# ...处理请求错误...
```
阅读全文