1、前言
随着自动化测试的普及与落地推广,出现了众多知名的自动化测试工具,如Selenium 、Robot Framework、Playwright等。本文将介绍一款在Python环境下的mechanize库,这个库能够模拟浏览器行为,支持发送HTTP请求、解析HTML页面和模拟用户输入等功能,非常适合开发自动化测试程序。
2、简介
在Python中进行有状态的程序化网页浏览。通过程序化浏览页面,轻松填写HTML表单和点击链接等操作,可以实现自动化测试、自动化爬虫等操作。
主要功能:
Github网址:
https://github.com/python-mechanize/mechanize
3、安装
1、正式版本:
pip3 install mechanize
2、开发版本:
git clone https://github.com/python-mechanize/mechanize.git
cd mechanize
pip3 install -e .
3、手动安装,只需在PYTHONPATH上的某处添加mechanize子目录。
4、快速上手
1、简单示例:
#!/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、官方示例:
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()
本文分享自 AllTests软件测试 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!