使用urllib在python中删除换行符


问题内容

我正在使用Python3.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导致raw_html变量过多的原因。


问题答案:

好像它们是文字\n字符,所以我建议您这样做。

raw_html2 = raw_html.replace('\\n', '')