Python机械化表单提交不起作用

时间:2015-11-22 20:11:58

标签: python html forms web mechanize

我试图整理一个python程序,该程序将定期从大学网站收集课程数据并将其保存到csv文件供个人使用。经过一番搜索,我偶然发现了机械化。我试图设置它以便我可以登录我的帐户,但我遇到了绊脚石。我在这里放在一起的代码应该提交包含登录信息的表单。该网站是https://idp-prod.cc.ucf.edu/idp/Authn/UserPassword。当提交的表单包含错误的登录信息时,响应页面应显示红色错误消息。我一直得到的反应缺乏这样的错误信息,我无法弄清楚我做错了什么。

import mechanize
from bs4 import BeautifulSoup
import cookielib
import urllib2

# log in page url
url = "https://idp-prod.cc.ucf.edu/idp/Authn/UserPassword"

# create the browser object and give it fake headers
myBrowser = mechanize.Browser()
myBrowser.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')]
myBrowser.set_handle_robots(False)

# have the browser open the site
myBrowser.open(url)

# handle the cookies
cj = cookielib.LWPCookieJar()
myBrowser.set_cookiejar(cj)

# select third form down
myBrowser.select_form(nr=2)

# fill out the form
myBrowser["j_username"] = "somestudentusername"
myBrowser["pwd"] = "somestudentpassword"

# submit the form and save the response
response = myBrowser.submit()

# upon the submission of incorrect login information an error message is displayed in red
soup = BeautifulSoup(response.read(), 'html.parser')
print (soup.find(color="red")) #find the error message in the response

0 个答案:

没有答案