Python登录网站不工作。。我想不通。刮网

2024-06-28 11:01:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python登录到一个网站,因为我要收集的一些数据需要登录。我的问题是,无论我如何编写代码,我都无法使登录脚本正常工作。。在

我的登录脚本代码如下:

import requests
import cookielib
import urllib
import urllib2

url = 'https://www.lectio.dk/lectio/94/login.aspx?lecafdeling=4733693087'
values = {'m_Content_username2' : '12z01',
          'm_Content_password2' : 'password', }

data = urllib.urlencode(values)
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()

loggedin = requests.get('https://www.lectio.dk/lectio/94/forside.aspx')
print loggedin.content

我也尝试了这个代码,我想我可能更喜欢使用:

^{pr2}$

他们都不管用。。。 我尝试登录的网站的html如下:

<input name="m$Content$username2" type="text" id="m_Content_username2" style="width: 130px" maxlength="20" onkeypress="capsDetect(event)" onkeyup="capsToggle(event)" onblur="capsReset(event)" autocomplete="off">

<input name="m$Content$password2" type="password" id="m_Content_password2" style="width: 130px" maxlength="50" onkeypress="capsDetect(event)" onkeyup="capsToggle(event)" onblur="capsReset(event)" autocomplete="off">

希望有人能帮我。。非常感谢。在


Tags: 代码import脚本event网站responsecontentopener
1条回答
网友
1楼 · 发布于 2024-06-28 11:01:38

你需要这样的东西:

import requests
from bs4 import BeautifulSoup

s = requests.session()

url = 'https://www.lectio.dk/lectio/94/login.aspx?lecafdeling=4733693087'
req = s.get(url)
bs = BeautifulSoup(req.content)

__EVENTVALIDATION = bs.find("input", {"name": "__EVENTVALIDATION"})['value']
__VIEWSTATEX = bs.find("input", {"name": "__VIEWSTATEX"})['value']

login_url = "https://www.lectio.dk/lectio/94/login.aspx?lecafdeling=4733693087"

data = {
    "__EVENTTARGET": "m$Content$submitbtn2",
    "m$Content$username2": "sdfsdf",
    "m$Content$password2": "sdfdsf",
    "__EVENTVALIDATION": __EVENTVALIDATION,
    "__VIEWSTATEX": __VIEWSTATEX
}

s.get(login_url)

loggedin = requests.get('https://www.lectio.dk/lectio/94/forside.aspx')
print loggedin.content

您可能还需要添加一些头,比如User Agent,我可能会错过一些CSRF和ASP.NET发布值。试试看。在

添加邮件头:

^{pr2}$

相关问题 更多 >