我需要解析一个包含“代码”标签的 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/