urllib read()更改属性

2024-05-14 09:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本的脚本,这是要求网站得到的html源代码。 在对几个网站进行爬网时,我发现源代码中的不同属性表示错误

示例:

from urllib import request

opener = request.build_opener()
with opener.open("https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2") as response:
    html = response.read()
print(html)

我将结果(htmlvar)与由Chrome和Firefox表示的源代码进行了比较

我看到了这样的区别:

Browser                        Urllib

href='rfc2616.html'            href=\'rfc2616.html\'
rev='Section'                  rev=\'Section\'
rel='xref'                     rel=\'xref\'
id='sec4.5'                    id=\'sec4.4\'

看起来urllib在这里放反斜杠来转义代码

这是一个深入内部的bug urllib还是有任何方法可以解决这个问题

提前谢谢


Tags: 脚本id源代码网站responserequesthtmlrev
1条回答
网友
1楼 · 发布于 2024-05-14 09:22:54

responce.read()将返回一个bytes对象,当打印时它的转义序列不会被解释,请参阅:

print(b'hello\nworld') # prints b'hello\nworld'

您需要decode将其转换为str,这样在打印时可以正确地计算转义:

print(html.decode())

相关问题 更多 >

    热门问题