gpt4 book ai didi

python - 抓取需要登录的网站

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:09 25 4
gpt4 key购买 nike

我正在尝试使用 BeautifulSoup 抓取网站。有问题的站点要求我登录。请查看我的代码。

from bs4 import BeautifulSoup as bs
import requests
import sys

user = 'user'
password = 'pass'

# Url to login page
url = 'main url'

# Starts a session
session = requests.session(config={'verbose': sys.stderr})

login_data = {
'loginuser': user,
'loginpswd': password,
'submit': 'login',
}

r = session.post(url, data=login_data)

# Accessing a page to scrape
r = session.get('specific url')
soup = bs(r.content)

我在这里看到一些线程后想出了这段代码,所以我想它应该是有效的,但打印的内容仍然好像我已注销一样。

当我运行这段代码时,会打印出:

2013-05-10T22:49:45.882000   POST   >the main url to login<
2013-05-10T22:49:46.676000 GET >error page of the main url page as if the logging in failed<
2013-05-10T22:49:46.761000 GET >the specific url<

当然,登录信息是正确的。需要一些帮助的人。

@编辑

我将如何在上面实现 header ?

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]

最佳答案

首先,您不应使用任何早于 1.2.0 的请求版本。如果您发现错误(您可能会发现),我们根本不会支持它们。

其次,您可能正在寻找的是:

import requests
from requests.packages.urllib3 import add_stderr_logger

add_stderr_logger()
s = requests.Session()

s.headers['User-Agent'] = 'Mozilla/5.0'

# after examining the HTML of the website you're trying to log into
# set name_form to the name of the form element that contains the name and
# set password_form to the name of the form element that will contain the password
login = {name_form: username, password_form: password}
login_response = s.post(url, data=login)
for r in login_response.history:
if r.status_code == 401: # 401 means authentication failed
sys.exit(1) # abort

pdf_response = s.get(pdf_url) # Your cookies and headers are automatically included

我注释了代码以帮助您。您也可以尝试@FastTurtle 关于使用 HTTP Basic Auth 的建议,但如果您首先尝试发布到表单,则可以继续按照我上面描述的方式进行尝试。还要确保 loginuserloginpswd 是正确的表单元素名称。如果不是,那可能是这里的潜在问题。b

关于python - 抓取需要登录的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16490773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com