发布评论的Ruby脚本

时间:2012-03-03 05:12:09

标签: ruby http http-post mechanize packet

我一直在尝试编写一个可以帮助我从命令行发表评论的脚本。(我想要这样做的唯一原因是它在这里的休假时间,我想要消磨时间)。 我经常访问this site并发帖。所以我只是从这个网站开始。 例如,对this post发表评论,我使用了以下脚本

require "uri"
require 'net/http'


def comment()
    response =  Net::HTTP.post_form(URI.parse("http://www.geeksforgeeks.org/wp-comments-post.php"),{'author'=>"pikachu",'email'=>"saurabh8c@gmail.com",'url'=>"geekinessthecoolway.blogspot.com",'submit'=>"Have Your Say",'comment_post_ID'=>"18215",'comment_parent'=>"0",'akismet_comment_nonce'=>"70e83407c8",'bb2_screener_'=>"1330701851 117.199.148.101",'comment'=>"How can we generalize this for a n-ary tree?"})
    return response.body
    end
puts comment()

显然,价值观并非硬编码,但为了清晰起见并保持帖子的目标,我正在硬编码。 除了表单上显示的常规字段之外,当我以正常方式发布评论时,我从wireshark发现了隐藏字段的值。我无法弄清楚我错过了什么?可能是一些js事件?

编辑: 很少有人建议使用 mechanize 我切换到python.Now我的更新代码如下:

import sys
import mechanize
uri = "http://www.geeksforgeeks.org/"
request = mechanize.Request(mechanize.urljoin(uri, "archives/18215"))
response = mechanize.urlopen(request)
forms = mechanize.ParseResponse(response, backwards_compat=False)
response.close()
form=forms[0]
print form
control = form.find_control("comment")
#control=form.find_control("bb2_screener")
print control.disabled
#  ...or readonly
print control.readonly
#  readonly and disabled attributes can be assigned to
#control.disabled = False
form.set_all_readonly(False)
form["author"]="Bulbasaur"
form["email"]="ashKetchup@gmail.com"
form["url"]="9gag.com"
form["comment"]="Y u no put a captcha?"
form["submit"]="Have Your Say"
form["comment_post_ID"]="18215"
form["comment_parent"]="0"
form["akismet_comment_nonce"]="d48e588090"
#form["bb2_screener_"]="1330787192 117.199.144.174"
request2 = form.click() 
print request2
try:
    response2 = mechanize.urlopen(request2)
except mechanize.HTTPError, response2:
    pass
# headers
for name, value in response2.info().items():
    if name != "date":
        print "%s: %s" % (name.title(), value)
print response2.read()  # body
response2.close()    

现在服务器返回this。在浏览原始页面的html代码时,我发现还有一个字段bb2_screener,如果我想假装像服务器的浏览器,我需要填写。但问题是字段没有写在标签内部,因此机械化不会将其视为字段。

1 个答案:

答案 0 :(得分:1)

假设您的所有参数都正确无误,那么您仍然缺少网站存储在Cookie中的会话信息。考虑使用像机械化这样的东西,它会为你处理cookie。你告诉它哪些字段填写哪些数据也更自然。如果仍然无法使用,你可以随时使用像硒这样的手提钻,但从技术上讲,你使用的是浏览器。