一、get请求
以爬取网址https://tieba.baidu.com/f?kw=海贼王&pn=250为例:
基本的用法:
import requests
url = 'https://tieba.baidu.com/f?'
params = {'kw':'海贼王','pn':'250'}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
html = requests.get(url=url,params=params,headers=headers)
print(html.text)
注意:
(1) url是最基本的url 不包含参数的
(2) params中的键值对为参数
优点:出现了中文,却不用处理。
结果:
一般的用法:
import requests
url = 'https://tieba.baidu.com/f?kw=海贼王&pn=250'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
response = requests.get(url,headers=headers)
print(response.text)
二、response.content 和response.text 的区别
(1)response.content 它是直接从网站上抓取数据,没有做任何的处理,返回的是字节流bytes;
处理方式:因为是字节流,所以解码一下就好了。
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
url = 'https://qq.yh31.com/zjbq/2920180.html'
response = requests.get(url,headers=headers)
print(response.content.decode('utf-8'))
结果:
(2)response.text 它是requests模块将 response.content编码之后所得到的数据,如果没有指定解码方式,requests就会猜一个解码的方式 (所以有可能猜对,有可能猜错),返回的是str
处理方式:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
url = 'https://qq.yh31.com/zjbq/2920180.html'
response = requests.get(url,headers=headers)
response.encoding = 'utf-8'
print(response.text)
结果: