在 python 中使用 urllib 时检测受密码保护的站点
您好,我有一系列很长的图像网址(例如 site.com/pic.jpg
),我正在为我的程序检索这些网址(在 Python v2.6 中)。我正在使用 urllib.urlretreive()。有时该网址会提示我输入用户名和密码。因此,我将 urllib.urlretreive() 放在 try/ except 中以避免这些 url,但我仍然需要插入假用户名和密码来提示触发 try/ except 跳过该 url 的错误。有没有一种方法可以让我感知何时有密码请求并自动跳过网址?这是一个很长的列表,我不想一直在这里等待偶尔按下回车键......谢谢
Hi I have a long series of urls of images (eg. site.com/pic.jpg
) which I am retrieving in order for my program (in Python v2.6). I'm using urllib.urlretreive()
. Sometimes the url prompts me for a username and password. So I placed urllib.urlretreive()
in a try/except to avoid those urls but I still need to insert a fake username and password to prompt the error that triggers the try/except to skip that url. Is there a way I can sense when there is a password request and skip the url automatically? It's a very long list and I don't want to be waiting here the whole time to push enter occasionally... Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果站点有 HTTP 身份验证,您需要在请求中添加标头以插入用户名和密码(假的或其他)。下面介绍了如何使用
urllib2
执行此操作。如果用户名/密码不正确,这将返回 urllib2.HTTPError: HTTP Error 401: Unauthorized,但如果不需要,服务器将忽略身份验证。
If the site has HTTP authentication, you need to add a header to your request to insert a username and password (fake or otherwise). Here's how you can do this using
urllib2
.This will return
urllib2.HTTPError: HTTP Error 401: Unauthorized
if the username/password is incorrect, but the server will ignore the authentication if it is not required.