在 python 中使用 urllib 时检测受密码保护的站点

发布于 2024-11-29 10:36:16 字数 295 浏览 2 评论 0原文

您好,我有一系列很长的图像网址(例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

永不分离 2024-12-06 10:36:16

如果站点有 HTTP 身份验证,您需要在请求中添加标头以插入用户名和密码(假的或其他)。下面介绍了如何使用 urllib2 执行此操作。

import base64
import urllib2

headers = {'Authorization': 'Basic ' + base64.encodestring('[username]:[password]')}
req = urllib2.Request(url, data, headers)
resp = urllib2.urlopen(req).read()

如果用户名/密码不正确,这将返回 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.

import base64
import urllib2

headers = {'Authorization': 'Basic ' + base64.encodestring('[username]:[password]')}
req = urllib2.Request(url, data, headers)
resp = urllib2.urlopen(req).read()

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文