【问题标题】:Python + Beautiful Soup: Write html source to filePython + Beautiful Soup:将 html 源代码写入文件
【发布时间】:2023-03-09 06:41:01
【问题描述】:

我正在尝试将页面源代码保存到一个文件中,这样我就不必在每次想要测试某些内容时都不断地重新运行我的代码。

我有:

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)),还是不行。

如何将内容写入文件?

【问题讨论】:

    标签: python file selenium-webdriver io beautifulsoup


    【解决方案1】:

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

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

    【讨论】:

    • 我认为这并不完全是这里发生的事情 - OP 使用 selenium 接近动态加载的网站,然后使用 BeautifulSoup 美化和“修复”从浏览器自动检索的 HTML 源代码selenium 并将生成的 HTML 保存在磁盘上。
    【解决方案2】:

    这对我有用:

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

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

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

    您现在应该可以使用浏览器打开它了。

    【讨论】:

    • 我认为这并不完全是这里发生的事情 - OP 使用 selenium 接近动态加载的网站,然后使用 BeautifulSoup 美化和“修复”从浏览器自动检索的 HTML 源代码selenium 并将生成的 HTML 保存在磁盘上。
    • @alecxe 将源保存到文件后,OP 不能美化和“修复”吗?我以为重点是获取源码,然后修改
    • 很可能 OP 想要保存由浏览器页面呈现的完整版本的美化版本,然后对该文件进行处理..不确定,让我们看看我们将从 OP 那里得到什么反馈.谢谢。
    • @alecxe 是的,我想保存美化版。现场。
    【解决方案3】:

    来自 bs4 documentation:

    UnicodeEncodeError: 'charmap' codec can't encode character u'\xfoo' in position bar(或几乎任何其他 UnicodeEncodeError) - 这不是 Beautiful Soup 的问题。这个问题主要表现在两种情况。首先,当您尝试打印控制台不知道如何显示的 Unicode 字符时。 (有关帮助,请参阅 Python wiki 上的此页面。)其次,当您写入文件并传入默认编码不支持的 Unicode 字符时。在这种情况下,最简单的解决方案是使用 u.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 编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多