Python + Beautiful Soup:编写html源文件



我试图将页面源代码保存到一个文件中,这样我就不必每次想要测试一些东西时都不断地重新运行代码。

我有:

html_source = driver.page_source
soup = BeautifulSoup(html_source, 'lxml') # added `lxml` only b/c I got a warning saying I should
soup = soup.prettify()
with open('pagesource.html', 'wb') as f_out:
    f_out.write(soup)
我得到的错误是:
UnicodeEncodeError: 'ascii' codec can't encode character u'xab' in position 223871: ordinal not in range(128)

我还尝试了f_out.write(str(soup)),但没有工作。

如何将内容写入文件?

BeautifulSoup用于解析Html而不是抓取它。如果可以导入urllib,请尝试导入urlretrieve:

import urllib
urllib.urlretrieve("http://www.example.com/test.html", "test.txt")

这个适合我:

import urllib2
html = urllib2.urlopen('http://www.example.com').read()

现在html包含了该url的源代码。

  with open('web.html', 'w') as f:
      f.write(html)

现在应该可以用浏览器打开了

From bs4 documentation:

UnicodeEncodeError: 'charmap'编解码器不能在位置栏编码字符u'xfoo'(或几乎任何其他UnicodeEncodeError) -这不是Beautiful Soup的问题。这个问题主要出现在两种情况下。首先,当您尝试打印控制台不知道如何显示的Unicode字符时。(请参阅Python wiki上的此页面以获取帮助。)第二,当你写入一个文件时,你传入一个默认编码不支持的Unicode字符。在这种情况下,最简单的解决方案是使用.encode("utf8")显式地将Unicode字符串编码为UTF-8。

我得到了同样的错误,并解决它使用:

soup = BeautifulSoup(page.content, 'html.parser', from_encoding="utf8")
with open(file_name_with_path, mode="w",  encoding="utf8") as code:
        code.write(str(soup2.prettify()))

应该避免以二进制模式写入。尝试使用mode="w"而不是mode="wb"。此外,您还必须指定以utf8编码编写文件。您的错误不是由于bs4,而是由于文件写入过程无法接受utf8编码。

最新更新