urllib.request.urlopen(url)验证权限

2024-04-19 04:13:43 发布

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

我已经玩了几天漂亮的汤和分析网页。我一直在使用一行代码,这是我的救世主在所有脚本,我写。代码行是:

r = requests.get('some_url', auth=('my_username', 'my_password')).

但是。。。

我想对(打开带有身份验证的URL)执行相同的操作:

(1) sauce = urllib.request.urlopen(url).read() (1)
(2) soup = bs.BeautifulSoup(sauce,"html.parser") (2)

我无法打开一个url并阅读需要身份验证的网页。 我如何实现这样的目标:

  (3) sauce = urllib.request.urlopen(url, auth=(username, password)).read() (3) 
instead of (1)

Tags: 代码脚本auth身份验证url网页readrequest
2条回答

您正在使用HTTP Basic Authentication

import urllib2, base64

request = urllib2.Request(url)
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

所以您应该base64对用户名和密码进行编码,并将其作为Authorization头发送。

看看官方文件中的HOWTO Fetch Internet Resources Using The urllib Package

# 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
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)

相关问题 更多 >