Python mechanize表单提交没有

2024-06-02 09:06:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个简单的机器人程序,它可以在页面上登录到我的帐户,然后对其他用户的图像进行评论。但是我不能得到正确的意见表提交工作。评论表单如下所示:

<form id="comment-form" action="#" onsubmit="postComment($(this).serialize(),'image',117885,229227); return false;">
    <input class="comment" type="text" size="40" name="comment" id="comment" />
    <input type="hidden" name="commentObj" value="9234785" />
    <input type="hidden" name="commentMode" value="image" />
    <input type="hidden" name="userid" value="12427" />
    <input class="submit" type="submit" value="Comment" />
</form>

我的代码如下

^{pr2}$

页面有两个表单,评论表单是第二个表单。所以我确信我选择了正确的形式。有人能解释一下为什么这不起作用吗?在


Tags: nameimageformid表单inputvaluetype
2条回答

表单提交过程中有一个javascript代码正在执行:

onsubmit="postComment($(this).serialize(),'image',117885,229227); return false;"

mechanize根本无法处理它,因为它不是浏览器,而且内部没有javascript引擎。在

可能的解决方案:

  • 高级方法-通过^{}webdriver使用真正的浏览器,并自动执行使用操作-向输入发送键,单击“提交”按钮等。示例代码:

    from selenium import webdriver
    
    driver = webdriver.Firefox()
    dirver.get('my_url_here')
    
    comment = driver.find_element_by_id('comment')
    comment.send_keys('hello')
    comment.submit()  # this would find an enclosing form and submit it
    
  • 研究在触发表单提交事件时向服务器发送的请求。然后,使用^{}自动执行请求。

希望有帮助。在

如果我理解得很好,你必须尝试用这个修改过的代码

br.select_form(nr = 1)
br['comment'] = 'hello'
br.submit()

相关问题 更多 >