MechanicalSoup - 与网站自动交互

文章目录


一、关于 MechanicalSoup



概览

一个Python的库,用于自动与网站交互。MechanicalSoup自动存储和发送cookie,遵循重定向,并可以遵循链接和提交表单。它不使用JavaScript。

MechanicalSoup是由 M Hickford 创建的,他是 Mechanize 库深度用户。 不幸的是 Mechanize 是不兼容的Python3直到2019年及其发展 停滞不前好几年了。MechanicalSoup提供了一个类似的API,建立在Python 巨人请求(对于 HTTP会话)和 BeautifulSoup(用于文档 导航)。自2017年以来,它是一个由小型公司积极维护的项目 团队包括@hemberger@moy


二、安装

PyPI下载并安装最新的正式版本:

shell 复制代码
pip install MechanicalSoup

GitHub下载并安装开发版本:

shell 复制代码
pip install git+https://github.com/MechanicalSoup/MechanicalSoup

从源代码安装(在当前工作目录中安装版本):

python 复制代码
python setup.py install

(在所有情况下,将--user添加到install命令中 安装在当前用户的主目录中。)


三、示例

示例/expl_qwant.py中获取结果的代码 Qwan搜索:

python 复制代码
"""Example usage of MechanicalSoup to get the results from the Qwant
search engine.
"""

import re
import mechanicalsoup
import html
import urllib.parse

# Connect to Qwant
browser = mechanicalsoup.StatefulBrowser(user_agent='MechanicalSoup')
browser.open("https://lite.qwant.com/")

# Fill-in the search form
browser.select_form('#search-form')
browser["q"] = "MechanicalSoup"
browser.submit_selected()

# Display the results
for link in browser.page.select('.result a'):
    # Qwant shows redirection links, not the actual URL, so extract
    # the actual URL from the redirect link:
    href = link.attrs['href']
    m = re.match(r"^/redirect/[^/]*/(.*)$", href)
    if m:
        href = urllib.parse.unquote(m.group(1))
    print(link.text, '->', href)

更多示例可在示例/中找到。

对于具有更复杂表单的示例(复选框、单选按钮和 文本区域),读取测试/test_browser.py测试/test_form.py


2024-09-24(二)

相关推荐
死也不注释3 天前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
程序员鱼皮3 天前
AI 应用开发,不就是调个接口么?
计算机·ai·程序员·互联网·编程·网站
4Forsee3 天前
【Android】View 交互的事件处理机制
android·交互
吴秋霖3 天前
主流反爬虫、反作弊防护与风控对抗手段
爬虫·算法·反爬虫技术
hui函数3 天前
scrapy框架-day02
后端·爬虫·python·scrapy
安卓开发者4 天前
鸿蒙Next ArkWeb网页交互管理:从基础到高级实战
华为·交互·harmonyos
用户051610461674 天前
爬虫 API 技术全解析:从原理到实战的高效数据采集指南
爬虫·api
酷飞飞4 天前
PyQt 界面布局与交互组件使用指南
python·qt·交互·pyqt
木头左4 天前
讯飞星火大模型Spark4.0Ultra的WebSocket交互实现解析
websocket·网络协议·交互