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

相关推荐
Go Dgg4 小时前
Go语言实现豆瓣电影Top250爬虫
开发语言·爬虫·golang
攻城狮7号5 小时前
Python爬虫第20节-使用 Selenium 爬取小米商城空调商品
开发语言·数据库·爬虫·python·selenium
人类群星闪耀时17 小时前
5G + AR:让增强现实真正“实时交互”起来
5g·ar·交互
奋斗者1号17 小时前
浏览器自动化与网络爬虫实战:工具对比与选型指南
运维·爬虫·自动化
2401_8319433220 小时前
Element Plus对话框(ElDialog)全面指南:打造灵活弹窗交互
前端·vue.js·交互
超周到的程序员1 天前
大模型项目:普通蓝牙音响接入DeepSeek,解锁语音交互新玩法
交互
q567315231 天前
Node.js数据抓取技术实战示例
爬虫·python·scrapy·node.js
.生产的驴1 天前
SpringBoot 集成滑块验证码AJ-Captcha行为验证码 Redis分布式 接口限流 防爬虫
java·spring boot·redis·分布式·后端·爬虫·tomcat
来自星星的坤2 天前
Python 爬虫基础入门教程(超详细)
开发语言·爬虫·python
浩皓素2 天前
Python网络爬虫:从入门到实践
爬虫·python