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(二)

相关推荐
傻啦嘿哟8 小时前
长效住宅代理IP:反爬虫战场上的隐形盾牌
爬虫·网络协议·tcp/ip
华科云商xiao徐10 小时前
冷门但好用的Python库写个爬虫代码
爬虫
华科云商xiao徐10 小时前
Koa+Puppeteer爬虫教程页面设计
爬虫
南無忘码至尊10 小时前
Unity 实现与 Ollama API 交互的实时流式响应处理
unity·游戏引擎·交互
Python×CATIA工业智造13 小时前
列表页与详情页的智能识别:多维度判定方法与工业级实现
爬虫·深度学习·pycharm
失败又激情的man1 天前
python之requests库解析
开发语言·爬虫·python
爬虫程序猿1 天前
利用爬虫按关键字搜索淘宝商品实战指南
android·爬虫
打酱油的;1 天前
爬虫-数据解析
爬虫
打酱油的;1 天前
爬虫-request处理get
爬虫·python·django
布语world1 天前
2025快手创作者中心发布视频python实现
爬虫·python