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

相关推荐
泡泡以安11 小时前
安卓高版本HTTPS抓包:终极解决方案
爬虫·https·安卓逆向·安卓抓包
q5673152313 小时前
Java Selenium反爬虫技术方案
java·爬虫·selenium
温轻舟14 小时前
3D词云图
前端·javascript·3d·交互·词云图·温轻舟
儿歌八万首1 天前
uniapp 和原生插件交互
uni-app·交互
巴里巴气1 天前
Python爬虫用Clash软件设置代理IP
爬虫·python·tcp/ip
皮皮灬虾1 天前
微信小程序下单页—地址列表页—新增地址页 页面交互
微信小程序·小程序·交互
우리帅杰10 天前
爬虫002-----urllib标准库
爬虫
RacheV+TNY26427811 天前
拼多多API限流机制破解:分布式IP池搭建与流量伪装方案
大数据·网络·人工智能·爬虫·python
mit6.82411 天前
[muduo] TcpConnection | 回调交互
c++·交互
Allen Bright11 天前
【JS-4.4-键盘常用事件】深入理解DOM键盘事件:提升用户交互体验的关键
javascript·计算机外设·交互