0

如果我有用户名和密码并检索 Cookie 以在 Python 3 中进一步使用,如何登录到网站说http://www.example.com/ ?

4

1 回答 1

0

这是我在 python 中用于登录网页的代码片段:

base_url = "http://www.example.com"
store = 01234
username = 'myusername'
password = 'mypassword'

post_data = {
        'hdnAction': 'LOGIN',
        'txtStoreID': '%s' % store,
        'txtLogin': '%s' % username,
        'txtpassword': '%s' % password,
        'txtNumLines':'10',
        'btnLogin':'Login',
        'hdnCount':'0'
}
params = urllib.urlencode(post_data)
request = urllib2.Request(base_url + "/", params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
#print "getting url: %s" % request.get_full_url()
response = urllib2.urlopen(request, params, 300)
xmldata = response.read()
redirects = re.compile('''window\.location\.href="(.*?)"''', re.DOTALL).findall(xmldata)
cookie = response.headers.get('Set-Cookie').split(';')[0].strip() + ";"
if len(redirects) > 0 :
    request = urllib2.Request(base_url + "%s" % redirects[0])
    print "getting url: %s" % request.get_full_url()
    request.add_header('cookie', cookie)
    response = urllib2.urlopen(request, None, 300)
    xmldata = response.read()

帖子数据中的那些东西是 HTML FORM 标签上的元素。查看他们的“名称”属性。

于 2013-06-19T20:17:28.767 回答