Python网络爬虫(五)——requests

requests 也是用于发起网络请求的一个 python 库。大致的逻辑差不多,接口可能有区别。

发送 get 请求

def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

上面的参数中:

  • url:表示类 Request 的对象
  • params:要发送给类 Request 的查询字符串,可以是字典、元组列表或者 bytes 数据,字典类型会自动转换为 url 编码,不需要再用 urlencode 进行显式编码
  • **kwargs:其中包含了 request 中的可选参数,如 verify 参数可以选择是否对请求网站的 SSL 证书进行验证
  • 返回值:为一个 Response<Response> 类对象

因为 get 请求的返回值为一个 Response<Response> 类对象,因此可以借用该类的属性来进行输出。

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}

url = "http://httpbin.org/ip"
response = requests.get(url)

print(response.text)
print(response.content)
print(response.url)
print(response.encoding)
print(response.status_code)
print(response.cookies.get_dict())

结果为:

{
  "origin": "42.3.28.223"
}

b'{\n  "origin": "42.3.28.223"\n}\n'
http://httpbin.org/ip
None
200
{}
  • 使用 response.text 可以获取响应内容,不用再经过解析,已经是 Unicode 格式的数据
  • 使用 response.content 可以获取响应内容,只不过是 bytes 数据,需要再次进行解析
  • 使用 response.url 可以获取完整的 url 地址
  • 使用 response.encoding 可以获取响应头字符编码格式
  • 使用 response.status_code 可以获取响应的状态码

该类还有其它属性和方法,具体的可以看手册或源码。

发送 post 请求

在 urllib 中,设置 request.Request 的 data 参数就能够将 get 请求转变为 post 请求,而在 requests 中的 post 请求可以直接通过 requests 类的 post 方法进行发送。

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}

login_url = "http://www.renren.com/ajaxLogin/login"
user_info = {"email": "用户名", "password": "密码"}

response = requests.post(login_url,headers=headers,data=user_info)

print(response.status_code)

结果为:

200

proxy

在 urllib 中需要借用 request 中的 ProxyHandler 方法设置代理,然后通过 request.build_open 构建 opener,借用 opener 进行请求。而在 requests 中则可以直接在 get 方法中添加 proxies 参数来设置代理。

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}

proxy = {'http':'101.132.190.101:80'}

url = "https://www.baidu.com/"
ipurl = "http://httpbin.org/ip"

response = requests.get(url,headers=headers,proxies=proxy)
ipres = requests.get(ipurl,headers=headers,proxies=proxy)

print(response.url)
print(response.status_code)
print(ipres.text)

结果为:

https://www.baidu.com/
200
{
  "origin": "101.132.190.101"
}

session

在 urllib 中,可以利用 opener 发送多个请求,而多个请求之间可以共享一部分信息,比如 cookie。而如果是在 requests 中,就可以使用类 session 对象来实现。

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
login_url = "http://www.renren.com/ajaxLogin/login"
target_url = 'http://www.renren.com/880151247/profile'
user_info = {"email": "用户名", "password": "密码"}

session = requests.session()
session.post(login_url,headers=headers,data=user_info)

response = session.get(target_url)

print(response.status_code)

with open('saved.html','w',encoding='utf-8') as fp:
    fp.write(response.text)

结果为:

200

除此之外还会将访问到的个人主页保存在本地。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值