前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mechanize - 自动化与HTTP web服务器的交互操作

mechanize - 自动化与HTTP web服务器的交互操作

作者头像
wangmcn
发布2024-06-26 12:31:34
880
发布2024-06-26 12:31:34
举报
文章被收录于专栏:AllTests软件测试AllTests软件测试

1、前言

随着自动化测试的普及与落地推广,出现了众多知名的自动化测试工具,如Selenium 、Robot Framework、Playwright等。本文将介绍一款在Python环境下的mechanize库,这个库能够模拟浏览器行为,支持发送HTTP请求、解析HTML页面和模拟用户输入等功能,非常适合开发自动化测试程序。

2、简介

在Python中进行有状态的程序化网页浏览。通过程序化浏览页面,轻松填写HTML表单和点击链接等操作,可以实现自动化测试、自动化爬虫等操作。

主要功能:

  • mechanize.Browser类实现了urllib2.OpenerDirector的接口,因此可以打开任何URL,不仅限于HTTP。
  • 简便的HTML表单填写。
  • 便捷的链接解析和跟踪。
  • 浏览器历史记录,.back()和.reload()方法。
  • Referer HTTP请求头已正确添加(可选)。
  • 自动遵守robots.txt。
  • 自动处理HTTP-Equiv和Refresh。

Github网址:

https://github.com/python-mechanize/mechanize

3、安装

1、正式版本:

代码语言:javascript
复制
pip3 install mechanize

2、开发版本:

代码语言:javascript
复制
git clone https://github.com/python-mechanize/mechanize.git
cd mechanize
pip3 install -e .

3、手动安装,只需在PYTHONPATH上的某处添加mechanize子目录。

4、快速上手

1、简单示例:

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

import mechanize

# 创建一个浏览器对象
br = mechanize.Browser()

# 设置请求头,伪装成浏览器
br.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36')]

# 设置各种处理器
br.set_handle_equiv(True) # 解析HTML文档中的meta http-equiv标签
br.set_handle_gzip(True) # 解压缩gzip编码的响应
br.set_handle_redirect(True) # 允许自动处理HTTP重定向
br.set_handle_referer(True) # 在请求头中添加Referer字段
br.set_handle_robots(False) # 不遵循robots.txt文件

# 设置自动刷新的处理,max_time是刷新等待的最长时间
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# 是否设置debug模式
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)

# 打开一个网页
br.open("https://mechanize.readthedocs.io/en/latest/")

# 选择搜索表单
br.select_form(id='rtd-search-form')

# 填写搜索关键词
br['q'] = 'python'

# 提交搜索表单
br.submit()

# 获取搜索结果页面内容
content = br.response().read()

# 打印
print(content)

运行后,打印的结果。

2、官方示例:

代码语言:javascript
复制
import re
import mechanize

br = mechanize.Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
print(br.title())
print(response1.geturl())
print(response1.info()) # headers
print(response1.read()) # body

br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm.
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
response2 = br.submit()

# print currently selected form (don't call .submit() on this, use br.submit())
print(br.form)

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()
response4 = br.reload() # fetches from server

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()
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-06-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AllTests软件测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档