【问题标题】:python autofill form in a webpage网页中的python自动填充表单
【发布时间】:2018-01-18 06:41:56
【问题描述】:

我正在尝试在具有单个文本框和发送按钮的网页中填写表单,html 看起来像这样

<form class="form-horizontal">
                        <div class="row">
                            <div class="col-md-12">
                                <div id="TextContainer" class="textarea-container">
                                    <textarea id="Text" rows="5" maxlength="700" class="form-control remove-border" style="background:none;"></textarea>
                                </div><button id="Send" class="btn btn-primary-outline" type="button" onclick="SendMessage()" style="margin-top:10px" data-loading-text="Loading..."><span class="icon icon-pencil"></span> Send</button>
                            </div>
                        </div>
                    </form>

我尝试使用 mechanize 提交带有此代码的表单

import re
from mechanize import Browser

br = Browser()
response=br.open("https://abcd.com/")
for f in br.forms():
    if f.attrs['class'] == 'form-horizontal':
        br.form = f
text = br.form.find_control(id="Text")
text.value = "something"
br.submit()

代码运行没有错误,但没有提交,我该怎么做?

这里是 SendMessage 函数

function SendMessage() {
    var text = $('#Text').val();
    var userId = $('#RecipientId').val();
    if (text.trim() === "")
    {
        $('#TextContainer').css('border-color', 'red');
    }
    else if (new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(text))
    {
        $('#TextContainer').css('border-color', 'red');
        $('#message').html("Links are not allowed in messages");
    }
    else
    {
        $('#Send').button('loading');
        $.ajax(
        {
            url: '/Messages/SendMessage',
            type: 'POST',
            cache: false,
            data:
            {
                __RequestVerificationToken: $('<input name="__RequestVerificationToken" type="hidden" value="CfDJ8MQSRebrM95Pv2f7WNJmKQWGnVR66zie_VVqFsquOCZLDuYRRBPP1yzk_755VDntlD3u0L3P-YYR0-Aqqh1qIjd09HrBg8GNiN_AU48MMlrOtUKDyJyYCJrD918coQPG0dmgkLR3W85gV6P4zObdEMw" />').attr('value'),
                userId: userId,
                text: text
            }

        });
    }

}

【问题讨论】:

    标签: python html forms webpage mechanize


    【解决方案1】:

    我怀疑问题是 HTML 表单中的提交按钮不是 type=submit - 所以当你调用 br.submit() 时,mechanise 将不知道该怎么做。解决方法是更改​​ HTML 网站上的按钮类型,或者告诉浏览器使用哪个按钮来提交表单:

    br.submit(type='button', id='Send')
    

    submit 方法采用与 HTML 表单 API 相同的参数,因此我建议查看 documentation 了解更多详细信息。

    更新

    这里的问题似乎是附加到按钮的 JavaScript 方法。 Mechanize 不支持调用 JavaScript 函数,因此您将无法仅使用 .submit() 方法提交表单。相反,最好的选择可能是读入SendMessage() JavaScript 函数,如果有人单击“发送”按钮,就会调用该函数,然后手动将其转换为 Python。在最好的情况下,它包含一个简单的 AJAX POST 请求,在 Python 中很容易实现。相关问题请look here

    第二次更新

    鉴于您问题中的新信息,尤其是 JavaScript 函数,您现在可以在 Python 脚本中手动实现 POST 请求。我建议使用Requests 模块,这将使实现更容易。

    import requests
    
    data = {
        "__RequestVerificationToken": "CfDJ8MQSRebrM95Pv2f7WNJmKQWGnVR66zie_VVqFsquOCZLDuYRRBPP1yzk_755VDntlD3u0L3P-YYR0-Aqqh1qIjd09HrBg8GNiN_AU48MMlrOtUKDyJyYCJrD918coQPG0dmgkLR3W85gV6P4zObdEMw",
        "userId": "something",
        "text": "something else"
    }
    
    response = requests.post("https://example.com/Messages/SendMessage", data=data)
    

    response 现在将包含可用于检查请求是否成功发出的响应。请注意,您可能需要使用 mechanize 读出__RequestVerificationToken,因为我怀疑它是在您每次打开网站时生成的。您可以使用html_source = br.read() 读出HTML 源代码,然后搜索__RequestVerificationToken 并尝试提取相应的值。

    【讨论】:

    • 它抛出这个错误mechanize._form.ControlNotFoundError: no control matching type 'button', kind 'clickable', id 'Send'
    • 尝试通过 ID 进行操作,即br.submit(id='Send'),看看是否可行?
    • 问题在于SendMessage() JavaScript 函数。我已经更新了我的答案,提出了如何解决这个问题的建议。
    • 我已经更新了函数,我也知道了userId但是验证令牌呢?
    • 我更新了回复,并提出了一些建议。
    【解决方案2】:

    您可以为您的文本区域赋予名称属性,例如:

    <form class="form-horizontal">
                            <div class="row">
                                <div class="col-md-12">
                                    <div id="TextContainer" class="textarea-container">
                                        <textarea id="Text" name="sometext" rows="5" maxlength="700" class="form-control remove-border" style="background:none;"></textarea>
                                    </div><button id="Send" class="btn btn-primary-outline" type="button" onclick="SendMessage()" style="margin-top:10px" data-loading-text="Loading..."><span class="icon icon-pencil"></span> Send</button>
                                </div>
                            </div>
                        </form>
    

    然后试试这个:

    import re
    from mechanize import Browser
    
    br = mechanize.Browser()
    br.open("https://abcd.com/")
    br.select_form(nr=0) #in case of just single form you can select form passing nr=0
    br["sometext"] = "something"
    response  = br.submit()
    print(response.read())
    

    如果它成功提交表单,那么您可以阅读您的回复正文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2011-10-22
      相关资源
      最近更新 更多