我已经设置了一个用于登录网站的脚本。挑战在于我在EC2上运行脚本,网站要求我通过向我发送自定义代码来进行额外的验证。
我立即收到了电子邮件,但需要能够动态更新该字段。
这是脚本
import urllib2
import urllib2
import cookielib
import urllib
import requests
import mechanize
from bs4 import BeautifulSoup
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_refresh(False)
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)
# 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')]
# The site we will navigate into, handling it's session
br.open('https://www.website.com/login')
#select the first form
br.select_form(nr=0)
#user credentials
br['user_key'] = 'username@gmail.com'
br['user_password'] = 'somePassw0rd'
# Login
br.submit()
#enter verification code
input_var = raw_input("Enter something: ")
#put verification code in form
br['Verication'] = str(input_var)
#submit form
br.submit()
我面临的挑战是我不断收到错误说:
AttributeError: mechanize._mechanize.Browser instance has no attribute __setitem__ (perhaps you forgot to .select_form()?)
如何才能按预期运行?
答案 0 :(得分:1)
br['Verication'] = str(input_var)
这是不正确的,因为使用br.submit()将使您的浏览器不再选择表单。
提交后我会尝试:for form in br.forms():
print form
查看是否有其他表格可供选择
阅读登录网站上的html代码,并检查确切点击登录时会发生什么。您可能必须在同一页面上重新选择表单,然后将验证码分配给其中一个控件