作用:发送网络请求,返回响应数据
安装:pip install requests
需求:通过requests向百度首页发送请求,获取百度首页的数据
import requests
# 目标url
url = 'https://www.baidu.com'
# 向目标url发送get请求
response = requests.get(url)
# 打印响应内容
print(response.text)
# 获取响应
res = requests.get(url, headers=headers)
print(res)
print(type(res))
# 获取请求的url, 响应的编码方式
print(res.url)
res.encoding = 'utf-8'
# 获取响应内容,会使用默认编码(有时候会乱码, 需要指定编码)
print(res.encoding)
print(res.text)
print(res.content.decode('utf-8'))
# 获取请求状态码
print(res.status_code)
# 获取响应对应的请求头
print(res.request.headers)
# 获取相应的cookie
print(res.cookies)
? 如果status_code小于200,response.ok返回True。
? 如果status_code大于200,response.ok返回False。
?
获取网页源码的通用方式:
response.content.decode()
response.content.decode('utf-8')
response.text
# 在百度首页搜索李小龙图片,然后下载到本地
import requests
url = 'https://photocdn.sohu.com/20080725/Img258368622.jpg'
res = requests.get(url)
with open('李小龙.jpg', 'wb') as f:
f.write(res.content)
import requests
url = 'https://photocdn.sohu.com/20080725/Img258368622.jpg'
# 请求
res = requests.get(url)
# 写入
with open('李小龙.jpg', 'wb') as f:
# 写入文件 注意:必须二进制形式
f.write(res.content)
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
url = 'https://i3.sinaimg.cn/ent/m/c/2010-11-26/U3987P28T3D3159293F326DT20101126121845.jpg'
# 请求
res = requests.get(url, headers=headers)
# 写入
with open('李小龙1.jpg', 'wb') as f:
f.write(res.content)
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
kw = {
'wd': '李小龙'
}
url = 'https://www.baidu.com/s?'
res = requests.get(url, params=kw, headers=headers)
print(res.content.decode('utf-8'))
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
url = 'https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_web_new_fanyi&sign=NyHAgRlbDg6%2BBbQIiKcntdRriqVIAJSQ%2BxmfU0q7dIE%3D'
# post 携带表单数据
form_data = {
'from': 'zh',
'to': 'en',
'q': '我爱你中国'
}
# 发送post请求
res = requests.post(url, data=form_data, headers=headers)
print(res.json())