【发布时间】:2012-03-21 13:40:06
【问题描述】:
我一直在尝试编写一个可以帮助我从命令行发表评论的脚本。(我想这样做的唯一原因是这里的假期时间,我想打发时间)。 我经常访问并在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。现在我更新的代码如下所示:
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。但是问题是该字段未写入标签内,因此机械化不会将其视为字段。
【问题讨论】:
-
您最好使用 HTTP 代理而不是使用 wireshark 来检查 HTTP 流量。我使用Charles,但Chrome中有一个内置工具,而Firefox有Firebug。话虽如此,您可能忘记将 cookie 与请求一起发送。
-
奇怪的是,您将机械化作为从 Ruby 切换的原因。 Ruby 有mechanize,它是一个特别好的实现(我在 python 和 perl 中都使用过 mechanize)。
-
好吧,我不知道机械化,所以我做的第一件事就是谷歌它。可用的第一个链接是基于 python。我对这两种语言都很满意。所以切换 :)顺便说一句,当我更多地尝试机械化时,我也发现了 perl 和 ruby 的库。但最终语言只是一种武器,它是程序员在战斗:)
标签: ruby http http-post mechanize packet