2014-10-08 62 views
2

我想写一个简单的机器人,它将登录到我的帐户在一个页面上,然后评论其他用户的图像。但是,我无法正确提交评论表单提交工作。注释形式如下: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> 

我的代码如下

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

页有两种形式和注释的形式是第二个。所以我相信我已经选择了正确的形式。任何人都可以解释为什么这不起作用?

+0

阐述了“不工作”的一部分可以显著增加你获得一个很好的答案的机会。 – bereal 2014-10-10 18:02:31

回答

3

有,而表单提交正在发生的事情正在执行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自动执行请求。

希望有所帮助。

0

如果我深知必须用本尝试改变代码

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