首页 > 解决方案 > 用 Python 模拟“点击”

问题描述

我已经阅读了所有主题,但不太清楚如何在 python 中模拟点击。我正在使用requests,但我不明白如何模拟它。

我需要“点击”的代码是:

<div class="container"> <a class="brand" href=url> <img src="logo2.png" alt="Logo"></a>
        <div class="page-container">
            <form class='addf' action="" method="post">
                <h1>url server</h1>


                <p>

                Welcome to url server!
                </p>
                                <input type="text" name="Username"  id="Username" readonly placeholder="Click to generate your username...">
                <input type="hidden" name="formid" value="32bbba790d2a75a5dafec2ec6c3bbc19" />

                <button name='urlline' type="submit">Generate now!</button>
            </form>
        </div>

提前感谢大家

标签: pythonbuttonclick

解决方案


如果您知道表单发布到哪个操作,您可以通过直接与Beautiful Soup结合发布来做到这一点。

行:<input type="hidden" name="formid" value="32bbba790d2a75a5dafec2ec6c3bbc19" />很重要,因为此哈希很可能是在提供页面时生成的。这样做是为了对抗 DDoS,例如有人向表单操作发送垃圾邮件请求。因此,为了让网络服务器接受您的请求,您必须检查此值并将其传递给您的 POST 请求。

你可以这样做:

import requests
from bs4 import BeautifulSoup


url = "http://some-url/"                              # replace with target URL
r  = requests.get(url)
if r.status_code == 200:
    bs = BeautifulSoup(r.text)
    form = bs.findAll("form", {"class": "addf"})[0]   # find the form

    inputs = form.findAll("input")                    # find the input-fields
    hash = None
    for input in inputs:
        if input.get("name") == "formid":             # find the hash
            hash = input.get("value")

    if hash:
        action = "createusername"                     # replace with target action
        res = requests.post(url + action, data={
            # ... other parameters, if any
            "formid" : hash
        })
        print(res)

您可能需要优化 Beautiful Soup 搜索 HTML 的方式,例如,如果多个元素具有class="addf".


推荐阅读