使用urll登录网页
IB2!但我的代码不能这样做!你可以帮我解决一下:我登录了吗? 网站:http://kenhhd.tv/user/login.html
我的代码是:
import urllib,cookielib
import urllib2,re,random,sys,datetime
import mechanize
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'RedditTesting')]
urllib2.install_opener(opener)
link_login = "http://kenhhd.tv/user/login.html?fast=true"
payload = {
'email': 'my_email@yahoo.com',
'password': 'my_pass'
}
data = urllib.urlencode(payload)
req = urllib2.Request(link_login,data)
resp = urllib2.urlopen(req)
contents = resp.read()
log = re.search(r'Tran the vinh',contents)
if log:
print "log-in is ok"
else:
print "erro"
答案 0 :(得分:0)
我建议您使用Python-Requests来自动处理Cookie(通过会话),这是一个例子:
from requests import Session
s = Session() # create a new Session which will handle the cookies
s.headers["User-Agent"] = "RedditTesting" # you wanted a custom user-agent, so here it is, it'll get applied to each request made with that session object
payload = {
"email":"email@domain.tld",
"password":"ExamplePassword",
"remember":"on", # additional parameters that I saw on the login page and may be needed
"_submit":"true" # same as above
}
r = s.post("http://kenhhd.tv/user/login.html", payload) # make the request
if "Tran the vinh" in r.text: # no need for regex if you just want to check if a string is in another string
print "logged in successfully"
else:
print "could not log in, something went wrong"