gpt4 book ai didi

http-headers - HTTP 基本身份验证不适用于 Python 3

转载 作者:行者123 更新时间:2023-12-04 23:38:20 27 4
gpt4 key购买 nike

我正在尝试访问启用了 HTTP 基本身份验证的 Intranet 站点。

这是我正在使用的代码:

from bs4 import BeautifulSoup
import urllib.request, base64, urllib.error

request = urllib.request.Request(url)
string = '%s:%s' % ('username','password')

base64string = base64.standard_b64encode(string.encode('utf-8'))

request.add_header("Authorization", "Basic %s" % base64string)
try:
u = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
print(e)
print(e.headers)

soup = BeautifulSoup(u.read(), 'html.parser')

print(soup.prettify())

但它不起作用并且失败了 401 Authorization required.我不明白为什么它不起作用。

最佳答案

给出的解决方案 here无需任何修改即可工作。

from bs4 import BeautifulSoup
import urllib.request

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
u = opener.open(url)

soup = BeautifulSoup(u.read(), 'html.parser')

前面的代码也能工作。您只需要解码 utf-8 编码的字符串,否则 header 包含字节序列。
from bs4 import BeautifulSoup
import urllib.request, base64, urllib.error

request = urllib.request.Request(url)
string = '%s:%s' % ('username','password')

base64string = base64.standard_b64encode(string.encode('utf-8'))

request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
try:
u = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
print(e)
print(e.headers)

soup = BeautifulSoup(u.read(), 'html.parser')

print(soup.prettify())

关于http-headers - HTTP 基本身份验证不适用于 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47157485/

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