Python爬虫:网络请求和处理问题实例
在Python中,我们可以使用requests库来发送HTTP请求并获取响应。以下是一些网络请求和处理问题的实例:
- 发送GET请求:
```python
import requests
response = requests.get(‘http://example.com‘)
print(response.text) # 打印响应内容
2. 发送POST请求:
```python
data = {'key': 'value'} # 请求数据
response = requests.post('http://example.com/api', data=data)
print(response.status_code, response.json()) # 打印状态码和返回数据
- 处理网络问题:
- 如果请求失败(如500内部服务器错误),可以捕获异常并尝试其他解决方案。
```python
try:
response = requests.get(‘http://example.com‘, timeout=10) # 设置超时时间
except requests.RequestException as e:
print(f”Error occurred: {e}”)
如果返回数据有问题(如JSON格式错误),可以使用json库进行检查和处理。
```
以上实例展示了Python爬虫中网络请求和处理问题的基本操作。根据实际需求,可以进一步完善和扩展功能。
还没有评论,来说两句吧...