带有验证的urllib.request.urlopen(url)

user7800892:

我一直在玩漂亮的汤并解析网页几天。我一直在使用一行代码,这是我编写的所有脚本中的救星。代码行是:

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

但是...

我想用(OPEN A URL WITH AUTHENTICATION)做同样的事情:

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

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

  (3) sauce = urllib.request.urlopen(url, auth=(username, password)).read() (3) 
instead of (1)
克里斯蒂安·科尼格(ChristianKönig):

看看官方文档中的如何使用urllib软件包获取Internet资源

# 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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何处理来自urllib.request.urlopen()的响应编码

我需要使用urllib2.Request / urlopen处理哪些错误/异常?

urllib.error.URLError:<urlopen错误未知的URL类型:'https>

urllib HTTPS请求:<urlopen错误未知的URL类型:https>

urllib.request.urlopen返回字节,但是我无法对其进行解码

HTTP错误401:未经授权使用urllib.request.urlopen

为什么有时urllib.request.urlopen不起作用,但浏览器起作用?

模拟urllib.request.urlopen的read函数返回MagicMock签名

kaggle内核:urllib.request.urlopen不适合任何URL

HTTPError问题:urllib.request.urlopen python请求错误

Python urllib.request.urlopen:AttributeError:“ bytes”对象没有属性“ data”

Python文档:urllib.request.urlopen(URL,data = None,[timeout,] *,cafile = None中的方括号是什么意思?

Python请求lib工作,urllib.request.urlopen POST不工作

python:urllib.request.urlopen不起作用

使用urllib.request查询带有一系列x-api-key标头的url

Python 3:urllib.request.urlopen和Progressbar

为什么在这种情况下urllib.request.urlopen会阻塞?

urllib,urllib2,urllib.request.open,AttributeError:“模块”对象没有属性“ urlopen”

替换urllib.request.urlopen(url,ca *)的开启器

urllib.request.urlopen(url)如何通过IP地址使用此功能?

urllib.request.urlopen无法获取堆栈溢出选举的主要页面

Python 3.6.2 url.request.urlopen() urllib.error.HTTPError:HTTP 错误 403:禁止

urllib.request.urlopen(url) 在 python 3 中不起作用

urllib.request 的 urlopen 无法在 python 3.7 中打开页面

urllib.request.urlopen 不适用于特定网站

如何使用 urllib.request.urlopen 从多个 url 获取所有图像 url

将 urllib.request.urlopen 移动到请求

python3中来自urllib.request的urlopen的奇怪行为

request.urlopen(url) 不返回网站响应或超时