网络机器人登录网站不工作



我正在尝试使用Python编写网络机器人,到目前为止我已经取得了一些成功,但是有一个机器人我遇到了问题。

这个机器人登录到hushmail.com,它将每隔几天通过cron运行,以确保帐户保持活跃。我使用mechanize填充表单,使用cookielib处理cookie和会话。这是从我找到的其他脚本中拼凑出来的。

在PyCharm中查看调试器输出时,表单填充正确,但是在提交第二页表单时,它没有像预期的那样将我带到收件箱。相反,它只是返回到相同的登录表单。

#!/usr/bin/env python
import mechanize
import cookielib
#login details
my_user="user@hush.com"
my_pass="sampplepass_sdfnsdfakhsk*876sdfj@("
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# Open some site, let's pick a random one, the first that pops in mind:
r = br.open('https://www.hushmail.com/')
html = r.read()
print br.title()
print r.info()
br.select_form(nr=0)
br.form['hush_username']=my_user
br.submit()
print br.title()
print r.info()
br.select_form('authenticationform')
br.form['hush_username']=my_user
br.form['hush_passphrase']=my_pass
br.submit()
print br.response().info()
print br.title()
print br.response().read()

我认为意外返回的HTML值是由于页面返回Javascript和HTML的混合,这在机械化解释上有问题。

我切换Python脚本使用Selenium Web Driver,它工作得更好。通过Firefox web驱动程序处理Javascript生成的HTML。我使用方便的Firefox Selenium IDE插件来记录我在浏览器中的操作,然后使用插件中的Export> Python Script来创建更强大的web bot的基础。

最新更新