1

我使用以下 Python 代码下载文件。这些代码在不需要登录名和密码时有效。目标文件将以theFile.

from urllib.request import urlopen
pageUrl = "https://en.wikipedia.org/robots.txt"
savePath="C:/Users/HMC/Desktop/theFile"
html = urlopen(pageUrl)
html_b = urlopen(pageUrl).read()
savefile(savePath, html_b)

但是,对于某些特定网站,需要登录名和密码。我www.fki.inf.unibe.ch举个例子,我已经有一个用户名myaccount012和密码mypw012(它们有效。你可以尝试登录/密码来访问浏览器中的文件)。

所以我改变pageUrl如下:

pageUrl = "http://myaccount012:mypw012@www.fki.inf.unibe.ch/DBs/iamDB/data/forms/a01-000u.png"

但是,当我运行代码时,我收到如下错误消息:-

InvalidURL: nonnumeric port: 'mypw012@www.fki.inf.unibe.ch'

我怎样才能修复它?非常感谢!

4

1 回答 1

0

该文档有一个 HTTP 基本身份验证的示例:

import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

因此,您需要添加一个 HTTPBasicAuthHandler 并使用正确的密码/用户名安装您自己的开启程序。

于 2018-07-19T20:41:05.380 回答