Python中最好用的爬虫库Requests代码实例

本文详细介绍了Python中Requests库的使用,包括通过Request对象发起请求、处理URL参数、获取Response对象、自定义请求头、POST请求、处理Cookie、使用会话对象、设置超时和SSL验证等。同时,展示了如何处理流式上传和异常处理,以及使用代理和适配器等高级特性。
摘要由CSDN通过智能技术生成

Request的代码实例


先导入模块
import requests.adapters

不同方式获取网页内容, 返回一个Response对象, 请求的参数可以为url或Request对象
r0 = requests.get("https://github.com/timeline.json")
r1 = requests.post("http://httpbin.org/post")
r2 = requests.put("http://httpbin.org/put")
r3 = requests.delete("http://httpbin.org/delete")
r4 = requests.head("http://httpbin.org/get")
r5 = requests.options("http://httpbin.org/get")
r6 = requests.patch("http://httpbin.org/get")
Request对象:

class requests.Request(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)

上边所有的获取方式都调用底层的request方法, 所以request方法有的参数, 上边几个函数都应该有:

requests.request(method, url, **kwargs)

kwargs包括: params / data / json / headers / cookies / files / auth / timeout / allow_redirects(bool) / proxies / verify(bool) / stream / cert

Response对象: class requests.Response

包含的主要属性: content / cookies / encoding / headers / history / is_permanent_redirect / is_redirect / reason / status_code / text / url 等

包含的主要方法:
iter_content(chunk_size=1, decode_unicode=False) / iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
包含的主要方法: close() / json(**kwargs) / raise_for_status() 等

以字典的形式传递URL参数, 也可以直接以?xx=xx&xx=xx的形式将其放在url后
params = {
  "key1": "value1", "key2": "value2"}
r = requests.get("http://httpbin.org/get", params=params)
print(r.url)                # http://httpbin.org/get?key2=value2&key1=value1
以字典的形式传递URL参数: 字典里带有列表

params = {
  "key1": "value1", "key2": ["value2", "value3"]}
r = requests.get("http://httpbin.org/get", params=params)
print(r.url)                # http://httpbin.org/get?key1=value1&key2=value2&key2=value3
获取网页内容
r = requests.get("https://github.com/timeline.json")
print(r.text)               # 返回正常的网页内容, 即解压解码之后的内容
print(r.content)            # 返回byte类型的网页内容, 即值解压, 没有解码
print(r.json())             # 如果网页内容为json, 直接返回一个json对象
print(r.encoding)           # 返回网页的编码: "utf-8"
Requests会自动解码来自服务器的内容, 也可以自己更改
r.encoding = "ISO-8859-1"
print(r.text)               # 此时使用新的r.encoding解码后的新值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值