【问题标题】:Python mechanize form submitting doesn't workPython机械化表单提交不起作用
【发布时间】:2014-10-08 17:54:38
【问题描述】:

我正在尝试编写一个简单的机器人,它可以在页面上登录我的帐户,然后评论其他用户的图像。但是我无法让提交的评论表单正常工作。评论表单如下所示:

<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>

我的代码如下

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

页面有两种形式,评论形式是第二种。所以我确信我选择了正确的表格。谁能解释为什么这不起作用?

【问题讨论】:

  • 详细说明“不起作用”部分可以显着增加获得好答案的机会。

标签: python web-scraping mechanize mechanize-python


【解决方案1】:

在提交表单时执行了一段 javascript 代码:

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

mechanize 根本无法处理它,因为它不是浏览器,也没有内置 javascript 引擎。

可能的解决方案:

  • 一种高级方法 - 通过selenium 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
    
  • 研究在触发表单提交事件时将哪些请求发送到服务器。然后,使用例如requests 自动执行请求。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    如果我理解得很好,您必须尝试使用​​此更改后的代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多