2013-06-19 28 views
0

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

+0

这取决于网站如何处理表单输入,用户名和密码。 – vidit

+0

说它是http://en.wikipedia.org/ – sgp

+0

了解什么是HTML表单,请阅读您感兴趣的网站的登录页面的HTML,以查看表单的外观以及它使用的HTTP方法,以及在请求中发送适当的头文件(如果需要的话)。没有人会为你做这件事。 – michaelmeyer

回答

0

下面的代码片段我在python用于登录到网页:

base_url = "http://www.example.com" 
store =
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表单标签元素。看看他们的“名字”属性。