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 ...
随机推荐
- Android线程管理之ExecutorService线程池
前言: 上篇学习了线程Thread的使用,今天来学习一下线程池ExecutorService. 线程管理相关文章地址: Android线程管理之Thread使用总结 Android线程管理之Execu ...
- 《转载》PAT 习题
博客出处:http://blog.csdn.net/zhoufenqin/article/details/50497791 题目出处:https://www.patest.cn/contests/pa ...
- Linux发邮件之mail命令
一.mail命令 1.配置 vim /etc/mail.rc 文件尾增加以下内容 set from=1968089885@qq.com smtp="smtp.qq.com" set ...
- [JavaEE笔记]Cookie
引言 由于 Http 是一种无状态的协议,服务器单从网络连接上无从知道客户身份. 会话跟踪是 Web 程序中常用的技术,用来跟踪用户的整个会话.常用会话跟踪技术是 Cookie 与 Session. ...
- 【那些年关于java多态应用】
1.多态:具有表现多种形态的能力的特征 父类: public abstract class Animal { public abstract void Say();} 子类: public class ...
- AC自动机-算法详解
What's Aho-Corasick automaton? 一种多模式串匹配算法,该算法在1975年产生于贝尔实验室,是著名的多模式匹配算法之一. 简单的说,KMP用来在一篇文章中匹配一个模式串:但 ...
- C# listview 单击列头实现排序 <二>
单击列头实现排序,首先在羡慕中添加下面的帮助实现的类:具体的代码: using System; using System.Collections; using System.Windows.Forms ...
- .Net语言 APP开发平台——Smobiler学习日志:Poplist控件的正确打开方式以及如何快速实现
最前面的话:Smobiler是一个在VS环境中使用.Net语言来开发APP的开发平台,也许比Xamarin更方便 样式一 一.目标样式 我们要实现上图中的效果,需要如下的操作: 1.从工具栏上的&qu ...
- python 数据类型 ---字符串
1. 字符串去除空白 ,strip() , 包括空格,tab键, 换行符 >>> name = " Frank " >>> name.strip ...
- linux(六)__进程与任务控制
一.程序.进程.线程 1.程序是一个普通文件,是一系列指令和数据的集合,是一个静态的实体,是程序员写好之后存储于外设之上的代码.它是"死"的,而进程和程序都是"活&quo ...