几天来,我一直在玩 beautifulsoup 和解析网页.我一直在使用一行代码,在我编写的所有脚本中,这是我的救星.代码行是:

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)

推荐答案

看看官方文件中的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)

Python-3.x相关问答推荐

如何将参数/值从测试方法传递给pytest的fixture函数?

对大型数据框中的选定列进行重新排序

如何提高 snowpark 程序的性能?

Python (pandas) - 判断一个 df 中的值是否在另一个(不相等)df 中的任何对之间

三重奏:为什么频道被记录为使用async with,而不是with?

将自动文本转换为 DataFrame

切片的Python复杂性与元组的星号相结合

为列表列表中的每个列表插入 str 到 index[0] 中. Python

将元组列表转换为以整个元组为键的字典列表

为什么 Multiprocessing 的 Lock 不会阻止其他进程使用对象?

为什么 setattr 在绑定方法上失败

基本 Flask 应用程序未运行(TypeError:模块中缺少必填字段type_ignores)

为 python3 安装 opencv

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

python asyncio - 如何等待取消的屏蔽任务?

python setup.py egg_info mysqlclient

如何在继承的数据类中创建可选字段?

如何替换 Python pathlib.Path 中的子字符串?

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python

将 Python 字节转换为无符号 8 位整数