python爬虫学习(6) —— 神器 Requests
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
更多用法请参考:
python爬虫学习(6) —— 神器 Requests的更多相关文章
- Python爬虫学习笔记-2.Requests库
Requests是Python的一个优雅而简单的HTTP库,它比Pyhton内置的urllib库,更加强大. 0X01 基本使用 安装 Requests,只要在你的终端中运行这个简单命令即可: pip ...
- python爬虫学习,使用requests库来实现模拟登录4399小游戏网站。
1.首先分析请求,打开4399网站. 右键检查元素或者F12打开开发者工具.然后找到network选项, 这里最好勾选perserve log 选项,用来保存请求日志.这时我们来先用我们的账号密码登陆 ...
- Python爬虫学习1: Requests模块的使用
Requests函数库是学习Python爬虫必备之一, 能够帮助我们方便地爬取. Requests: 让HTTP服务人类. 本文主要参考了其官方文档. Requests具有完备的中英文文档, 能完全满 ...
- python爬虫学习 —— 总目录
开篇 作为一个C党,接触python之后学习了爬虫. 和AC算法题的快感类似,从网络上爬取各种数据也很有意思. 准备写一系列文章,整理一下学习历程,也给后来者提供一点便利. 我是目录 听说你叫爬虫 - ...
- python爬虫学习笔记(一)——环境配置(windows系统)
在进行python爬虫学习前,需要进行如下准备工作: python3+pip官方配置 1.Anaconda(推荐,包括python和相关库) [推荐地址:清华镜像] https://mirrors ...
- Python爬虫利器一之Requests库的用法
前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...
- python爬虫学习01--电子书爬取
python爬虫学习01--电子书爬取 1.获取网页信息 import requests #导入requests库 ''' 获取网页信息 ''' if __name__ == '__main__': ...
- python爬虫学习05-爬取图片
python爬虫学习05-爬取图片 确定要爬取的网址:https://shenan.tuchong.com/20903415/#image309854686 要爬取的内容:使用浏览器插件xpath对图 ...
- python爬虫学习(1) —— 从urllib说起
0. 前言 如果你从来没有接触过爬虫,刚开始的时候可能会有些许吃力 因为我不会从头到尾把所有知识点都说一遍,很多文章主要是记录我自己写的一些爬虫 所以建议先学习一下cuiqingcai大神的 Pyth ...
随机推荐
- 【.net 深呼吸】将目录树转化为文本
大伙都知道,文件系统是树形结构的,有时候我们会想到把目录的层次结构变为纯文本形式,就像这样: ├─Windows-universal-samples-master │ ├─Samples │ │ ├─ ...
- Android自定义控件之自定义属性
前言: 上篇介绍了自定义控件的基本要求以及绘制的基本原理,本篇文章主要介绍如何给自定义控件自定义一些属性.本篇文章将继续以上篇文章自定义圆形百分比为例进行讲解.有关原理知识请参考Android自定义控 ...
- SparkStreaming实现Exactly-Once语义
作者:Syn良子 出处:http://www.cnblogs.com/cssdongl 转载请注明出处 译自:http://blog.cloudera.com/blog/2015/03/exactly ...
- Both must set "document.domain" to the same value to allow access.
有两个域名指向我的网站,其中一个域名访问我的网站的话就可以看到日期控件 另一个域名访问我的网站不能看到日期控件, 在EF中使用日期控件,浏览器审查元素后看到,报这个错误“Both must set & ...
- C#——this关键字(1)
//我的C#是跟着猛哥(刘铁猛)(算是我的正式老师)<C#语言入门详解>学习的,微信上猛哥也给我讲解了一些不懂得地方,对于我来说简直是一笔巨额财富,难得良师! 在学习C#的时候,老师讲的示 ...
- 记录一次bug解决过程:mybatis中$和#的使用
一.总结 mybatis中使用sqlMap进行sql查询时,经常需要动态传递参数.动态SQL是mybatis的强大特性之一,也是它优于其他ORM框架的一个重要原因.mybatis在对sql语句进行预编 ...
- BroadcastReceiver几种常见监听
1.BroadcastReceiver监听拨号 <intent-filter android:priority="1000" > <action android: ...
- spider RPC管理接口
为了在独立管理模式下尽可能的容易运行时排查问题,spider中间件提供了一系列restful api用于动态管理当前节点的路由,下游节点等.目前支持的RESTFUL API如下所示: 功能 服务号 R ...
- PowerDesigner 常用设置
1.使用 JDBC 方式连接 Oracle 逆向生成数据库 PDM 使用 ODBC 方式连接 Oracle 数据库可以借鉴这位兄弟的博客:http://www.cnblogs.com/clivehua ...
- switch语句的妙用
switch语句的普通用法很简单,如下: var a = 3; switch (a) { case 1: console.log(a); break; case 2: case 3: console. ...