【Python爬虫】爬虫利器 requests 库小结,字节跳动+阿里+华为+腾讯等大厂Python面试题
在Python中,requests库是一个非常流行的用于发起网络请求的库。以下是一些requests库的常用方法和示例代码:
- 发送GET请求:
import requests
response = requests.get('https://www.example.com')
print(response.text)
- 发送POST请求:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com/post', data=payload)
print(response.text)
- 添加请求头:
import requests
headers = {'User-Agent': 'My User Agent 1.0'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text)
- 使用cookies:
import requests
cookies = {'cookie_key': 'cookie_value'}
response = requests.get('https://www.example.com', cookies=cookies)
print(response.text)
- 处理响应:
import requests
response = requests.get('https://www.example.com')
# 状态码
print(response.status_code)
# 头部信息
print(response.headers)
# 返回的内容
print(response.text)
# 二进制内容
print(response.content)
# JSON内容
print(response.json())
- 超时处理:
import requests
response = requests.get('https://www.example.com', timeout=5)
print(response.text)
- 异常处理:
import requests
try:
response = requests.get('https://www.example.com')
response.raise_for_status() # 如果不是200,抛出HTTPError异常
except requests.exceptions.HTTPError as errh:
print(errh)
except requests.exceptions.ConnectionError as errc:
print(errc)
except requests.exceptions.Timeout as errt:
print(errt)
except requests.exceptions.RequestException as err:
print(err)
- 使用会话对象:
import requests
session = requests.Session()
session.auth = ('user', 'pass')
session.get('https://www.example.com/page1')
response = session.get('https://www.example.com/page2')
print(response.text)
以上是requests库的一些常用方法和示例代码,这些代码可以帮助开发者快速发起网络请求,处理响应数据,以及实现简单的爬虫功能。
评论已关闭