Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

所以我们来看下Requests库吧!

0. 安装Requests

0.1 Distribute & Pip ¶

使用 pip 安装Requests非常简单

 pip install requests

0.2 获得源码 ¶

下载源码:

curl -OL https://github.com/kennethreitz/requests/zipball/master

解压并切换到该目录下,进行安装:

python setup.py install

1 使用Requests

1.1 抓取某个页面

使用urllib2抓取一个页面,我们是这样的:

import urllib2
test = urllib2.urlopen('http://bigballon.github.io/').read()
print test

而使用requests,我们有如下代码:

import requests
r = requests.get('http://bigballon.github.io/')
print r.text

1.2 增加headers

某些页面可能需要我们的爬虫伪装成浏览器才可以访问。还是拿hdu来举例,我们有如下代码:

import urllib2
headers = {
'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
}
req = urllib2.Request(
url = 'http://acm.hdu.edu.cn/',
data = None,
headers = headers
)
html = urllib2.urlopen(req).read()
print html

而直接使用requests呢,我们还是只需要这样写:

import requests
r = requests.get("http://acm.hdu.edu.cn/")
print r.text

1.3 需要登陆的情况

要登陆到HDU,我们可能要写一大串代码:

import urllib2, urllib, cookielib
import re, HTMLParser host_url = 'http://acm.hdu.edu.cn/'
post_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' # 伪装成浏览器
headers = {
'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
}
# 生成请求,这里访问hdu的主页,而不是登陆url,这里只是为了获取cookie
# 因为hdu做了反爬虫,所有必须加入headers才能访问
req_host = urllib2.Request(
url = host_url,
headers = headers
)
# 获取cookie
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen(req_host).read()
# 生成post请求所需要的表单数据
# 账号密码换成你自己的
postdata=urllib.urlencode({
'username':'China_Lee',
'userpass':'xxxxx',
'login':'Sign In'
}) # 生成post所需的请求
req_post = urllib2.Request(
url = post_url,
data = postdata,
headers = headers
)
# 发送请求,登陆成功
result = urllib2.urlopen(req_post).read()

但是我们使用requests呢:

import requests
data = {'username':'China_Lee','userpass':'XXXXX','login':'Sign In'}
cookies = dict(cookies_are='working')
url = 'http://acm.hdu.edu.cn/userloginex.php?action=login'
r = requests.post(url,data=data,cookies=cookies)

2. 实例对比

我们曾经写过一个获取指定 runid 下的AC代码的小 DEMO

#coding=utf-8
import urllib2, urllib, cookielib
import re, HTMLParser host_url = 'http://acm.hdu.edu.cn/'
post_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' # 伪装成浏览器
headers = {
'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
}
# 生成请求,这里访问hdu的主页,而不是登陆url,这里只是为了获取cookie
# 因为hdu做了反爬虫,所有必须加入headers才能访问
req_host = urllib2.Request(
url = host_url,
headers = headers
)
# 获取cookie
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen(req_host).read()
# 生成post请求所需要的表单数据
# 账号密码换成你自己的
postdata=urllib.urlencode({
'username':'China_Lee',
'userpass':'xxxxx',
'login':'Sign In'
}) # 生成post所需的请求
req_post = urllib2.Request(
url = post_url,
data = postdata,
headers = headers
)
# 发送请求,登陆成功
result = urllib2.urlopen(req_post).read() # 声明一个HTMLParser实例
html_parser = HTMLParser.HTMLParser() # 制定某一个代码页面
# 注意,这个页面是我自己找到,是我自己的AC代码,如果你使用这个页面,是没有权限的,请换一个你所AC的代码所在的URL
req_code = urllib2.Request(
url = 'http://acm.hdu.edu.cn/viewcode.php?rid=14880688',
headers = headers
)
# 读取页面内容
down_html = urllib2.urlopen(req_code).read() # 分析页面后得到正则表达式
pattern = re.compile('<textarea id=usercode style="display:none;text-align:left;">(.+?)</textarea>',re.S)
# 使用正则表达式匹配code
down_code = pattern.findall(down_html)[0]
# 使用unescape处理html中的转义字符
code = html_parser.unescape(down_code)
# 使用replace处理\r\n,windows下和linux下并不相同
code = code.replace('\r\n','\n')
# 将代码存储为test.cpp
open('test.cpp',"w").write(code)

现在我们用requests来改写:

#coding=utf-8
import re, HTMLParser, requests
s = requests.session()
html_parser = HTMLParser.HTMLParser() cookies = dict(cookies_are='working')
post_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login'
data = {'username':'China_Lee','userpass':'XXXXX','login':'Sign In'}
# 登陆
r = s.post(post_url,data=data,cookies=cookies) code_url = 'http://acm.hdu.edu.cn/viewcode.php?rid=14880688'
down_html = s.get(code_url,cookies=cookies).text pattern = re.compile('<textarea id=usercode style="display:none;text-align:left;">(.+?)</textarea>',re.S)
down_code = pattern.findall(down_html)[0]
code = html_parser.unescape(down_code)
code = code.replace('\r\n','\n')
open('test.cpp',"w").write(code)

是的,就是这样的,requests是相当好用的。

3. TODO

更多用法请参考:

  1. Python爬虫利器一之Requests库的用法
  2. 官方文档——快速上手

python爬虫学习(6) —— 神器 Requests的更多相关文章

  1. Python爬虫学习笔记-2.Requests库

    Requests是Python的一个优雅而简单的HTTP库,它比Pyhton内置的urllib库,更加强大. 0X01 基本使用 安装 Requests,只要在你的终端中运行这个简单命令即可: pip ...

  2. python爬虫学习,使用requests库来实现模拟登录4399小游戏网站。

    1.首先分析请求,打开4399网站. 右键检查元素或者F12打开开发者工具.然后找到network选项, 这里最好勾选perserve log 选项,用来保存请求日志.这时我们来先用我们的账号密码登陆 ...

  3. Python爬虫学习1: Requests模块的使用

    Requests函数库是学习Python爬虫必备之一, 能够帮助我们方便地爬取. Requests: 让HTTP服务人类. 本文主要参考了其官方文档. Requests具有完备的中英文文档, 能完全满 ...

  4. python爬虫学习 —— 总目录

    开篇 作为一个C党,接触python之后学习了爬虫. 和AC算法题的快感类似,从网络上爬取各种数据也很有意思. 准备写一系列文章,整理一下学习历程,也给后来者提供一点便利. 我是目录 听说你叫爬虫 - ...

  5. python爬虫学习笔记(一)——环境配置(windows系统)

    在进行python爬虫学习前,需要进行如下准备工作: python3+pip官方配置 1.Anaconda(推荐,包括python和相关库)   [推荐地址:清华镜像] https://mirrors ...

  6. Python爬虫利器一之Requests库的用法

    前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...

  7. python爬虫学习01--电子书爬取

    python爬虫学习01--电子书爬取 1.获取网页信息 import requests #导入requests库 ''' 获取网页信息 ''' if __name__ == '__main__': ...

  8. python爬虫学习05-爬取图片

    python爬虫学习05-爬取图片 确定要爬取的网址:https://shenan.tuchong.com/20903415/#image309854686 要爬取的内容:使用浏览器插件xpath对图 ...

  9. python爬虫学习(1) —— 从urllib说起

    0. 前言 如果你从来没有接触过爬虫,刚开始的时候可能会有些许吃力 因为我不会从头到尾把所有知识点都说一遍,很多文章主要是记录我自己写的一些爬虫 所以建议先学习一下cuiqingcai大神的 Pyth ...

随机推荐

  1. 使用AWS亚马逊云搭建Gmail转发服务(一)

    title: 使用AWS亚马逊云搭建Gmail转发服务(一) author:青南 date: 2014-12-30 15:41:35 categories: Python tags: [Gmail,A ...

  2. div中设置滚动条的问题

    <div srtle="width:100px;height:50px;"></div> 这样的一个div,当文本超出的时候我们就会设: overflow: ...

  3. xdebug断点调试原理

    通过Xdebug进行远程调试时,PHPSTORM等IDE会监听Xdebug设置的调试ip和端口(php.ini中配置) [xdebug] ; Xdebug zend_extension=php_xde ...

  4. Java设计模式之策略模式(Strategy)

    前言: 最近一直在学习基于okHttp网络请求,学习的过程中就想起了之前项目中有这么一个需求不同的接口要采用不同的加密方式,比如登录之前要采用RSA加密,登录之后要采用AES加密,当时是采用靠传递一个 ...

  5. 【Python五篇慢慢弹】数据结构看python

    数据结构看python 作者:白宁超 2016年10月9日14:04:47 摘要:继<快速上手学python>一文之后,笔者又将python官方文档认真学习下.官方给出的pythondoc ...

  6. 自己封装了一个EF的上下文类.,分享一下,顺便求大神指点

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  7. Java正则速成秘籍(一)之招式篇

    导读 正则表达式是什么?有什么用? 正则表达式(Regular Expression)是一种文本规则,可以用来校验.查找.替换与规则匹配的文本. 又爱又恨的正则 正则表达式是一个强大的文本匹配工具,但 ...

  8. 完美解决,浏览器下拉显示网址问题 | 完美解决,使用原生 scroll 写下拉刷新

    在 web 开发过程中我们经常遇到,不想让用户下拉看到我的地址,也有时候在 div 中没有惯性滚动,就此也出了 iScroll 这种关于滚动条的框架,但是就为了一个体验去使用一个框架好像又不值得,今天 ...

  9. iFrame 功能详解

    目录索引: 一. 简介二. 属性三. 功能四. 应用 一.简介 网页“帧”的概念最早是由Netscape所提出,当时全部由“帧”构成的页面,也被称之为 “框架集”页面,在一个“框架集”页面中,“帧” ...

  10. Linq在Array,List,Dictionary中的应用

    Linq在Array,List,Dictionary中的应用 今天在实际工作中需要对array,list,dictionary进行排序,试一试linq,发现非常好用,代码如下: using Syste ...