1.get请求:
不携带参数的get请求
不携带参数的get请求 + headers
携带参数的get请求 + headers
2.post请求: 构建参数的post请求
3.响应数据的获取与属性
(1).响应数据的获取:
res.text: 文本数据
res.json(): json数据
res.content: 流
(2).向应的其他属性:
res.status_code: 获取响应状态码
res.headers: 响应头
res.cookie: cookie信息
# 不携带参数的get请求: 爬取搜狗主页
import requests
url = 'https://www.sogou.com/'
res = requests.get(url=url)
print(res)
print(res.text)
with open('sougou.html', 'w', encoding='utf-8') as f:
f.write(res.text)
# 不携带参数的get请求 + headers: 爬取知乎的发现页
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}
url = 'https://www.zhihu.com/explore'
res = requests.get(url=url, headers=headers)
with open('zhihu.html', 'w', encoding='utf-8') as f:
f.write(res.text)
# 携带参数的get请求 + headers: 知乎的发现栏中搜索Python
import requests
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}
url= 'https://www.zhihu.com/search?'
params = {
'type':'content',
'q':'python'
}
res = requests.get(url=url, headers=headers, params=params)
print(res)
print(res.text)
with open('python.html', 'w', encoding='utf-8') as f:
f.write(res.text)
重点掌握GET & POST: GET与POST的区别
1、GET请求中的参数包含在URL里面,数据可以在URL中看到,而POST请求的URL不回包含这些数据,POST的数据
都是通过表单形式传输的。会包含在请求体中
2、GET请求提交的数据最多只有1024字节,而POST方式没有限制
3、post请求比get请求相对安全
# requests的post请求: 以post方式请求httpbin.org/post时会返回提交的请求信息
import requests
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}
url = 'http://httpbin.org/post'
data = {
'name': 'spiderman',
'age': 8
}
res = requests.post(url=url, headers=headers, data=data)
print(res.text)