我对Python非常陌生,我正在尝试让web页面的源代码与HTML元素一起工作。在
但是,当我把字节转换成utf-8
时,一些HTML代码就消失了。这是我的代码:
import urllib.request
req = urllib.request.Request('http://avast.softonic.com/')
response = urllib.request.urlopen(req)
the_page = response.read()
例如,在“theu page”中ID为“review_data”的DIV的内容是:
^{pr2}$但当我尝试做以下任何事情时:
import urllib.request
req = urllib.request.Request('http://avast.softonic.com/')
response = urllib.request.urlopen(req)
the_page = response.read()
html_missing_elements = the_page.decode('utf-8')
或者:
import requests
r =requests.get('http://avast.softonic.com/')
html_missing_elements = r.text
或者:
import urllib.request
from bs4 import BeautifulSoup
req = urllib.request.Request('http://avast.softonic.com/')
response = urllib.request.urlopen(req)
the_page = response.read()
html_missing_elements = BeautifulSoup(the_page)
在下面的示例中,ID为“review_data”的DIV只包含:
<div id="review_data" class="track_links"><br /><!--[/conclusion]--></p></div>
我不能得到完整的原始HTML网页代码,有代码丢失,我想知道为什么。在
谢谢。在
html中嵌入了一些回车符,即
\r
:还有更多。在
删除后,IDE中的所有内容都将正常工作,打印时可以看到标记内容:
^{pr2}$数据实际上在那里,您的IDE只是没有显示它,因为回车:
使用pycharm将输出:
但是使用:
将输出:
如果要使用ipython运行相同的代码,则只需使用
soup = BeautifulSoup(r.content,"lxml")
即可看到正确的输出:它与编码无关,它只是回车符在您运行代码的任何地方干扰输出。运行下面的一个简单示例,您可以看到如何影响输出:
相关问题 更多 >
编程相关推荐