BeautifulSoup本身不支持自定义HTML标签,因为它是一个HTML解析库,只能解析符合HTML标准的文档。
但是,你可以使用BeautifulSoup的parse
方法,将自定义标签解析为一个普通的HTML标签,然后再使用BeautifulSoup进行解析。
以下是一个示例:
from bs4 import BeautifulSoup
# 自定义HTML文档
custom_html = '''
Custom HTML
Hello, world!
'''
# 将自定义标签解析为普通的HTML标签
custom_html = custom_html.replace('', '').replace('', '')
# 使用BeautifulSoup进行解析
soup = BeautifulSoup(custom_html, 'html.parser')
# 获取自定义标签内容
custom_tag = soup.find('div')
print(custom_tag.text)
输出:
Hello, world!
在上面的示例中,我们将自定义标签 请注意,这只是一种解决方案,具体实现方式可能因实际需求而有所不同。
替换为find
方法找到自定义标签,通过text
属性获取其内容。
相关内容