【问题标题】:Extract single div from HTML and save in place. TypeError: expected a character buffer object从 HTML 中提取单个 div 并保存到位。 TypeError:期望一个字符缓冲区对象
【发布时间】:2014-12-10 11:15:19
【问题描述】:

我正在尝试编写一个简单的 Python 脚本来继续我对 BeautifulSoup/Python 的学习。

我想要的功能很简单,我想从 HTML 文件中提取 div 并更新 HTML 文件以仅包含该 div 的内容。例如,如果我的 HTML index.html 包含:

<head> 
  <title> Parsing HTML </title> 
</head>
<body>
  <h1> Title </h1>

  <div class="content"> 
    <p> This is the content </p> 
    <img src="img.jpg" />
  </div>
</body>

我的程序运行后,我希望 index.html 只包含

 <div class="content"> 
        <p> This is the content </p> 
        <img src="img.jpg" />
 </div>

所以&lt;div class="content"&gt; 将被用作一个参数来确定在 HTML 中提取的位置。

我猜你需要使用 BeautifulSoup 来写这个,这是我的尝试(对于上面的代码)。我也试过让它递归:

import os
from bs4 import BeautifulSoup

def CleanUpFolder(dir):
    directory = os.listdir(dir)
    files = []

    for file in directory:
        if file.endswith('.html'):
            files.insert(0, file)
        if os.path.isdir(file):
            CleanUpFolder(file)
        for fileName in files:
            file = open(dir + "\\" + fileName)
            content = file.read()
            file.close()
            soup = BeautifulSoup.BeautifulSoup(content)
            toWrite = soup.find("div", {"class": "main"})
            file = open(dir + "\\" + fileName, 'w')
            file.write(toWrite)
            file.close()


dir = "C:\Users\Folder\Desktop\\testFolder"
CleanUpFolder(dir)

我的错误是:

Traceback(最近一次调用最后一次): 文件“C:/Users/Admin/PycharmProjects/Extract-Main-2.py”,第 25 行,在 清理文件夹(目录)

第 25 行是最后一行,CleanUpfolder(dir)

我不明白是什么原因造成的。

和-

文件“C:/Users/Admin/PycharmProjects/Extract-Main-2.py”,第 20 行,在 CleanUpFolder file.write(toWrite) TypeError: 期望一个字符缓冲区对象

这是我从 BeautifulSoup 文档上的一些示例代码中得到的,所以不明白为什么它不起作用。

非常感谢任何帮助/反馈 - 特别是解释,因为我发现 BeautifulSoup 比我应该理解的要困难得多!

谢谢:)

【问题讨论】:

    标签: python html parsing python-2.7 beautifulsoup


    【解决方案1】:

    你应该

    import bs4
        ...
    soup = bs4.BeautifulSoup(content)
    

    from bs4 import BeautifulSoup
        ...
    soup = BeatifulSoup(content)
    

    问题是由于尝试在 BeautifulSoup 4 上运行从 BeautifulSoup 3 编写的代码(导入为 BeautifulSoup)引起的。这两个模块都包含一个名为 BeautifulSoup() 的函数,您的代码应该调用该函数。

    【讨论】:

    • 非常感谢你,这是我的一个愚蠢的疏忽,现在已修复:)
    猜你喜欢
    • 2012-09-17
    • 2017-04-18
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多