前体:我昨天在这里问了一个类似的问题。我不编辑该问题的原因是,尽管两者相似,但这个问题要先进得多。
我的项目:我想使用 Python 登录到一个安全网站,导航到该会话中的多个页面并将这些页面中的文本提取到一个文件中。
详细信息:这是我收集的所有信息/我编写的代码。
以下是安全站点登录页面中值得注意的部分:
<form action="index.asp" method="post" name="form">
<input type="text" id="user" name="user"">
<input type="password" name="password">
<input type="hidden" name="logon" value="username">
<input type="submit" name="submit" value="Log In" class="button">
</form>
页面上还有 javascript 代码检查 cookie,所以我知道我需要cookielib.CookieJar()
.
大编辑
我正在导入以下模块:urllib
、urllib2
和.cookielib
nltk
生成以下代码:
cookiejar = cookielib.CookieJar()
# Notice I set 'debug' to 'true'.
debug = True
handlers = [
urllib2.HTTPHandler(debuglevel=debug),
urllib2.HTTPSHandler(debuglevel=debug),
urllib2.HTTPCookieProcessor(cookiejar),
]
opener = urllib2.build_opener(*handlers)
# These headers I copied directly from Chrome's Developer Tools
opener.addheaders = [
("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"),
("Accept-Encoding", "gzip,deflate,sdch"),
("Accept-Language", "en-US,en;q=0.8"),
("Cache-Control", "max-age=0"),
("Connection", "keep-alive"),
("Content-Type", "application/x-www-form-urlencoded"),
("Host", "www.myebill.com"),
("Origin", "https://www.myebill.com"),
("Referer", "https://www.myebill.com/index.asp?startnam"),
("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36")
]
urllib2.install_opener(opener)
# Passing the form data as a URL-encoded string
payload = "user=<User>&password=<Password>&logon=username&submit=Log+In"
req = urllib2.Request("https://www.myebill.com/index.asp", data=payload)
cookiejar.add_cookie_header(req)
page = urllib2.urlopen(req)
pdata = page.read()
print( nltk.clean_html( pdata ) )
注意:如果您希望我发布调试输出,请询问。:)
我的问题:运行我的代码后,我仍然收到“您的会话已超时或您未正确登录”。信息。
请帮忙?我尝试学习机械化,但似乎我能在网上找到的唯一文档令人费解且令人困惑。任何建议或代码将不胜感激。
另外,当我找到答案时,我承诺将我的完整代码作为编辑发布给任何需要它作为参考的人!(省略登录信息,当然..)