python爬虫主要模块-requests

reuqests

requests是使用Apache2 licensed 许可证的HTTP库。
可使用其发起http请求,比urllib2模块更简洁。

一、Get请求

r = requests.get(url,headers=headers,cookies=cookie)

传递参数

你也许经常想为 URL 的查询字符串(query string) 传递某种数据。如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。例如, www.baidu.com/?key=val。 Requests 允许你使用 params 关键字参数

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("https://www.baidu.com/", params=payload)
print(r.url)
https://www.baidu.com/?key2=value2&key1=value1

定制请求头

url = 'https://www.baidu.com/s?wd=python'
headers = {
        'Content-Type': 'text/html;charset=utf-8',
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
    }
r = requests.get(url,headers=headers)

使用代理

proxies = {'http':'ip1','https':'ip2' }
requests.get('url',proxies=proxies)

二、 Post请求

HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式,服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码

常见的编码方式
  • form表单:application/x-www-form-urlencoded

  • json字符串:application/json

url = 'http://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post(url, data=json.dumps(payload))
#print(r.text)
print(r.headers.get('Content-Type'))

application/json
  • 用于上传文件:multipart/form-data
url = 'http://httpbin.org/post'
files = {'file': open('report.txt', 'rb')}
r = requests.post(url, files=files)
print(r.text)


{
...
  "files": {
    "file": "hello world"
  }, 
  "form": {}, 
  "headers": {
    "Content-Type": "multipart/form-data; boundary=6db46af64e694661985109da21c8fe9b", 

  }, 
  "json": null, 
  "origin": "223.72.217.138", 
  "url": "http://httpbin.org/post"
  ...
}

三、常用对象

  • r.url:打印输出该 URL

  • r.headers:以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None

  • r.requests.headers:返回发送到服务器的头信息

  • r.status_code:返回连接状态码

  • r.content:以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩

  • r.json:把网页中的json数据转成字典并将其返回

  • r.encoding:获取当前的编码

  • r.raise_for_status:失败请求(非200响应)抛出异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值