Web bot 登录网站不工作

Web bot to login to site not working

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

此机器人登录 hushmail.com,它将每隔几天 运行 通过 cron 来确保帐户保持活动状态。我正在使用 mechanize 来填写表格,使用 cookielib 来处理 cookie 和会话。它是从我发现的其他脚本中拼凑而成的。

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

#!/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()

我认为意外的 return HTML 值是由于页面 return 混合了 Javascript 和 HTML 而机械化在解释时有问题.

我将 Python 脚本切换为使用 Selenium Web Driver which works much better. handling Javascript generated HTML via a Firefox web driver. I used the handy Selenium IDE plugin for Firefox 在浏览器中记录我的操作,然后使用插件中的 Export > Python 脚本来创建更多的基础强大的网络机器人。