python - 如何告诉 BeautifulSoup 将特定标签的内容提取为文本? (不碰它)

标签 python syntax-highlighting beautifulsoup

我需要解析一个包含“代码”标签的 html 文档

我得到这样的代码块:

soup = BeautifulSoup(str(content))
code_blocks = soup.findAll('code')

问题是,如果我有这样的代码标签:
<code class="csharp">
    List<Person> persons = new List<Person>();
</code>

BeautifulSoup 强制关闭嵌套标签并将代码块转换为:
<code class="csharp">
    List<person> persons = new List</person><person>();
    </person>
</code>

有什么方法可以使用 BeautifulSoup 将代码标签的内容提取为文本,而不让它修复 IT 认为的 html 标记错误?

最佳答案

将代码标记添加到 QUOTE_TAGS 字典。

from BeautifulSoup import BeautifulSoup

content = "<code class='csharp'>List<Person> persons = new List<Person>();</code>"

BeautifulSoup.QUOTE_TAGS['code'] = None
soup = BeautifulSoup(str(content))
code_blocks = soup.findAll('code')

输出:
[<code class="csharp"> List<Person> persons = new List<Person>(); </code>]

关于python - 如何告诉 BeautifulSoup 将特定标签的内容提取为文本? (不碰它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922969/

相关文章:

syntax-highlighting - 从不同的编辑器将语法突出显示导入 Joe Editor?

python - 获取具有任意嵌套度的 html 元素的内容(以及内容的 xpath)

python - 当父级位于隐式命名空间中时,BeautifulSoup 会删除子级

python - BeautifulSoup 正则表达式

python - 无法获取 tkinter 中在类里面制作的内容

git - git 提交消息的 vim 语法突出显示 - 自定义 commentchar

python - pytorch:计算向量函数的向量雅可比积

r - Github的Gedit语法高亮样式方案?

python - 通过动态键名对字典进行分组并聚合Python中嵌套字典的一些键

python - 此操作的正确语法是什么?