mechanize (1)
最近看的关于网络爬虫和模拟登陆的资料,发现有这样一个包
mechanize ['mekə.naɪz]又称为机械化的意思,确实文如其意,确实有自动化的意思。
mechanize.Browser and mechanize.UserAgentBase implement the interface of urllib2.OpenerDirector, so:
any URL can be opened, not just
http:mechanize.UserAgentBaseoffers easy dynamic configuration of user-agent features like protocol, cookie, redirection androbots.txthandling, without having to make a newOpenerDirectoreach time, e.g. by callingbuild_opener().Easy HTML form filling.
Convenient link parsing and following.
Browser history (
.back()and.reload()methods).The
RefererHTTP header is added properly (optional).Automatic observance of
robots.txt.Automatic handling of HTTP-Equiv and Refresh.
意思就是说 mechanize.Browser和mechanize.UserAgentBase只是urllib2.OpenerDirector的接口实现,因此,包括HTTP协议,所有的协议都可以打开
另外,提供了更简单的配置方式而不用每次都创建一个新的OpenerDirector
对表单的操作,对链接的操作、浏览历史和重载操作、刷新、对robots.txt的监视操作等等
import re
import mechanize
(1)实例化一个浏览器对象
br = mechanize.Browser()
(2)打开一个网址
br.open("http://www.example.com/")
(3)该网页下的满足text_regex的第2个链接
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
assert br.viewing_html()
(4)网页的名称
print br.title()
(5)将网页的网址打印出来
print response1.geturl()
(6)网页的头部
print response1.info() # headers
(7)网页的body
print response1.read() # body
(8)选择body中的name =" order"的FORM
br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm.
(9)为name = cheeses的form赋值
br["cheeses"] = ["mozzarella", "caerphilly"] # (the method here is __setitem__)
# Submit current form. Browser calls .close() on the current response on
# navigation, so this closes response1
(10)提交
response2 = br.submit() # print currently selected form (don't call .submit() on this, use br.submit())
print br.form
(11)返回
response3 = br.back() # back to cheese shop (same data as response1)
# the history mechanism returns cached response objects
# we can still use the response, even though it was .close()d
response3.get_data() # like .seek(0) followed by .read()
(12)刷新网页
response4 = br.reload() # fetches from server (13)这可以列出该网页下所有的Form
for form in br.forms():
print form
# .links() optionally accepts the keyword args of .follow_/.find_link()
for link in br.links(url_regex="python.org"):
print link
br.follow_link(link) # takes EITHER Link instance OR keyword args
br.back()
这是文档中给出的一个例子,基本的解释已经在代码中给出
You may control the browser’s policy by using the methods of mechanize.Browser’s base class, mechanize.UserAgent. For example:
通过mechanize.UserAgent这个模块,我们可以实现对browser’s policy的控制,代码给出如下,也是来自与文档的例子:
br = mechanize.Browser()
# Explicitly configure proxies (Browser will attempt to set good defaults).
# Note the userinfo ("joe:password@") and port number (":3128") are optional.
br.set_proxies({"http": "joe:password@myproxy.example.com:3128",
"ftp": "proxy.example.com",
})
# Add HTTP Basic/Digest auth username and password for HTTP proxy access.
# (equivalent to using "joe:password@..." form above)
br.add_proxy_password("joe", "password")
# Add HTTP Basic/Digest auth username and password for website access.
br.add_password("http://example.com/protected/", "joe", "password")
# Don't handle HTTP-EQUIV headers (HTTP headers embedded in HTML).
br.set_handle_equiv(False)
# Ignore robots.txt. Do not do this without thought and consideration.
br.set_handle_robots(False)
# Don't add Referer (sic) header
br.set_handle_referer(False)
# Don't handle Refresh redirections
br.set_handle_refresh(False)
# Don't handle cookies
br.set_cookiejar()
# Supply your own mechanize.CookieJar (NOTE: cookie handling is ON by
# default: no need to do this unless you have some reason to use a
# particular cookiejar)
br.set_cookiejar(cj)
# Log information about HTTP redirects and Refreshes.
br.set_debug_redirects(True)
# Log HTTP response bodies (ie. the HTML, most of the time).
br.set_debug_responses(True)
# Print HTTP headers.
br.set_debug_http(True) # To make sure you're seeing all debug output:
logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO) # Sometimes it's useful to process bad headers or bad HTML:
response = br.response() # this is a copy of response
headers = response.info() # currently, this is a mimetools.Message
headers["Content-type"] = "text/html; charset=utf-8"
response.set_data(response.get_data().replace("<!---", "<!--"))
br.set_response(response)
另外,还有一些类似于mechanize的网页交互模块,
There are several wrappers around mechanize designed for functional testing of web applications:
归根到底,都是对urllib2的封装,因此,选择一个比较好用的模块就好了!
mechanize (1)的更多相关文章
- Python使用mechanize模拟浏览器
Python使用mechanize模拟浏览器 之前我使用自带的urllib2模拟浏览器去进行訪问网页等操作,非常多站点都会出错误,还会返回乱码.之后使用了 mechanize模拟浏览器,这些情况都没出 ...
- 使用Mechanize实现自动化表单处理
使用Mechanize实现自动化表单处理 mechanize是对urllib2的部分功能的替换,能够更好的模拟浏览器行为,在web访问控制方面做得更全面 mechanize的特点: 1 http, ...
- Ruby:Mechanize的使用教程
小技巧 puts Mechanize::AGENT_ALIASES 可以打印出所有可用的user_agent puts Mechanize.instance_methods(false) 输出Mech ...
- python使用mechanize模拟登陆新浪邮箱
mechanize相关知识准备: mechanize.Browser()<br># 设置是否处理HTML http-equiv标头 set_handle_equiv(True)<br ...
- python之mechanize模拟浏览器
安装 Windows: pip install mechanize Linux:pip install python-mechanize 个人感觉mechanize也只适用于静态网页的抓取,如果是异步 ...
- pyhton mechanize 学习笔记
1:简单的使用 import mechanize # response = mechanize.urlopen("http://www.hao123.com/") request ...
- Mechanize抓取数据【Ruby】
创建: 2017/08/05 更新: 2018/01/08 修正: ele_inner_text -> ele.inner_text 补充: ...
- Python的50个模块,满足你各种需要
Python具有强大的扩展能力,我列出了50个很棒的Python模块,包含几乎所有的需要:比如Databases,GUIs,Images, Sound, OS interaction, Web,以及其 ...
- BruteXSS:XSS暴力破解神器
×01 BruteXSS BruteXSS是一个非常强大和快速的跨站点脚本暴力注入.它用于暴力注入一个参数.该BruteXSS从指定的词库加载多种有效载荷进行注入并且使用指定的载荷和扫描检查这些参数很 ...
随机推荐
- POJ 3126 Prime Path (素数+BFS)
题意:给两个四位素数a和b,求从a变换到b的最少次数,每次变换只能变换一个数字并且变换的过程必须也是素数. 思路:先打表求出四位长度的所有素数,然后利用BFS求解.从a状态入队,然后从个位往千位的顺序 ...
- POJ 2010 Moo University - Financial Aid (优先队列)
题意:从C头奶牛中招收N(奇数)头.它们分别得分score_i,需要资助学费aid_i.希望新生所需资助不超过F,同时得分中位数最高.求此中位数. 思路: 先将奶牛排序,考虑每个奶牛作为中位数时,比它 ...
- maven的三种工程pom、jar、war
阅读数:739 maven中的三种工程: 1.pom工程:用在父级工程或聚合工程中.用来做jar包的版本控制. 2.war工程:将会打包成war,发布在服务器上的工程.如网站或服务. 3.jar工程: ...
- 朴素贝叶斯分类算法介绍及python代码实现案例
朴素贝叶斯分类算法 1.朴素贝叶斯分类算法原理 1.1.概述 贝叶斯分类算法是一大类分类算法的总称 贝叶斯分类算法以样本可能属于某类的概率来作为分类依据 朴素贝叶斯分类算法是贝叶斯分类算法中最简单的一 ...
- POJ1417 True Liars 并查集 动态规划 (种类并查集)
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - POJ1417 题意概括 有一群人,p1个好人,p2个坏人. 他们说了n句话.(p1+p2<=600,n ...
- Android 之 <requestFocus />
EditText中的 <requestFocus />标记?? 第一个<requestFocus />会获得焦点,意思就是如果你给某个edittext设置了<reques ...
- symmfony
安装:http://symfony.cn/docs/book/installation.html 1先检查php版本是否符合你要下载的symfony的最低版本: php -version 系统安装完成 ...
- python str,list,tuple转换
1. str转listlist = list(str) 2. list转strstr= ''.join(list) 3. tuple list相互转换tuple=tuple(list)list=l ...
- Web侦察工具HTTrack (爬取整站)
Web侦察工具HTTrack (爬取整站) HTTrack介绍 爬取整站的网页,用于离线浏览,减少与目标系统交互,HTTrack是一个免费的(GPL,自由软件)和易于使用的离线浏览器工具.它允许您从I ...
- 函数式编程之 Python
上接 python 函数式编程学习笔记 参考:www.sigai.cn/ 1 函数式编程概述 前提:函数在 Python 中是⼀等对象 工具:built-in ⾼阶函数:lambda 函数:opera ...