我正在使用Python 3.x。使用时urllib.request
要下载网页,我得到了很多\n
之间。我正在尝试使用论坛其他线程中给出的方法删除它,但我无法这样做。我用过strip()
函数和replace()
功能...但没有运气!我在 eclipse 上运行这段代码。这是我的代码:
import urllib.request
#Downloading entire Web Document
def download_page(a):
opener = urllib.request.FancyURLopener({})
try:
open_url = opener.open(a)
page = str(open_url.read())
return page
except:
return""
raw_html = download_page("http://www.zseries.in")
print("Raw HTML = " + raw_html)
#Remove line breaks
raw_html2 = raw_html.replace('\n', '')
print("Raw HTML2 = " + raw_html2)
我无法找出获得大量的原因\n
in the raw_html
多变的。
Your download_page()
函数破坏了 html (str()
打电话)这就是为什么你会看到\n
(两个字符\
and n
)在输出中。不要使用.replace()
或其他类似的解决方案,修复download_page()
函数代替:
from urllib.request import urlopen
with urlopen("http://www.zseries.in") as response:
html_content = response.read()
在此刻html_content
包含一个bytes
目的。要将其作为文本获取,您需要知道其字符编码,例如,从Content-Type
http标头:
encoding = response.headers.get_content_charset('utf-8')
html_text = html_content.decode(encoding)
See 在 Python 中获取 HTTP 响应的字符集/编码的好方法.
如果服务器没有传入字符集Content-Type
标题然后有计算 html5 文档中字符编码的复杂规则例如,它可以在 html 文档中指定:<meta charset="utf-8">
(你需要一个 html 解析器来获取它)。
如果你正确地阅读了 html 那么你不应该看到文字字符\n
在页面中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)