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

相关推荐
Jason-河山3 分钟前
Java爬虫抓取数据的艺术
java·爬虫·python
啧不应该啊3 小时前
Python爬虫bs4基本使用
爬虫·python·selenium
B站计算机毕业设计超人4 小时前
计算机毕业设计Hadoop+Spark知识图谱体育赛事推荐系统 体育赛事热度预测系统 体育赛事数据分析 体育赛事可视化 体育赛事大数据 大数据毕业设计
大数据·hadoop·爬虫·spark·知识图谱·数据可视化·推荐算法
B站计算机毕业设计超人5 小时前
计算机毕业设计Hadoop+PySpark深圳共享单车预测系统 PyHive 共享单车数据分析可视化大屏 共享单车爬虫 共享单车数据仓库 机器学习 深度学习
数据仓库·hive·hadoop·爬虫·机器学习·spark·数据可视化
我是大头鸟10 小时前
Python 使用selenium 4.25 进行爬虫(1)
爬虫·python·selenium
jiaoxingk18 小时前
不会JS逆向也能高效结合Scrapy与Selenium实现爬虫抓取
javascript·爬虫·python·selenium·scrapy
李宥小哥18 小时前
微信小程序03-页面交互
微信小程序·交互·notepad++
DngYT20 小时前
request库的使用 | get请求
爬虫
XUE_DING_E1 天前
趣笔阁爬虫实验
爬虫·python