Requests简单入门

发送GET请求

  1. 最简单的发送get请求就是通过requests.get来实现
response=requests.get("http://www.baidu.com/")
  1. 添加headers和查询参数:
    如果想添加 headers,可以传入headers参数来增加请求头中的headers信息。如果要将参数放在url中传递,可以利用 params 参数。相关示例代码如下:
 import requests

 kw = {
    
    'wd':'中国'}

 headers = {
    
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}

 # params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
 response = requests.get("http://www.baidu.com/s", params = kw, headers = headers)

 # 查看响应内容,response.text 返回的是Unicode格式的数据
 print(response.text)

 # 查看响应内容,response.content返回的字节流数据,为btype类型
 print(response.content)

 # 查看完整url地址
 print(response.url)

 # 查看响应头部字符编码
 print(response.encoding)

 # 查看响应码
 print(response.status_code) 

python的字符串在硬盘和网络传输过程中都是编码后的数据,所以数据类型都为btype

response.text和response.content的区别:

  • response.content:这个是直接从网络上面抓取的数据。没有经过任何解码。所以是一个bytes类型。其实在硬盘上和在网络上传输的字符串都是bytes类型。
  • response.text:这个是str的数据类型,是requests库将response.content进行解码的字符串。解码需要指定一个编码方式,requests会根据自己的猜测来判断编码的方式。所以有时候可能会猜测错误,就会导致解码产生乱码。这时候就应该使用例如response.content.decode(‘utf-8’)进行手动解码。

demo

#抓取页面保存到本地
import requests

#查询字符串
params = {
    
    
    'wd':'中国'
}
headers={
    
    
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
res = requests.get('http://www.baidu.com/s',params=params,headers=headers)
with open('baidu.html','w',encoding='utf-8') as fp:
    #指定解码方式
    fp.write(res.content.decode('utf-8'))

print(res.url)

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/105671755