Skip to main content
 首页 » 编程设计

python之使用 urllib 删除 python 中的换行符

2025年05月04日9me-sa

我正在使用 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) 

我无法找出在 raw_html 变量中获取大量 \n 的原因。

请您参考如下方法:

你的 download_page()函数破坏了 html(str() 调用),这就是您看到 \n 的原因(两个字符 \ 和 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 header :

encoding = response.headers.get_content_charset('utf-8') 
html_text = html_content.decode(encoding) 

参见 A good way to get the charset/encoding of an HTTP response in Python .

如果服务器没有在 Content-Type 中传递字符集标题然后有complex rules to figure out the character encoding in html5 document例如,可以在 html 文档中指定:<meta charset="utf-8"> (你需要一个 html 解析器来获取它)。

如果您正确阅读了 html,那么您应该看不到文字字符 \n在页面中。