gpt4 book ai didi

python - 如何使用BeautifulSoup匹配
中嵌入的文本?

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:12 25 4
gpt4 key购买 nike

我在 test.py 中有以下 BeautifulSoup 代码。

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1:

from bs4 import BeautifulSoup

import sys
soup = BeautifulSoup(sys.stdin.read(), 'html.parser', from_encoding='utf-8')

import re
from pprint import pprint
pprint(soup.find('div', text=re.compile(r'Scientific')))

这里有两个 html 文件:

测试1.html

<div class="heading4">Scientific/Research Contact(s)</div>

test2.html

<div class="heading4"><a name="_Scientific/Research_Contact(s)"></a>Scientific/Research Contact(s)</div>

这是搜索结果。

$ ./test.py < test1.html
<div class="heading4">Scientific/Research Contact(s)</div>
$ ./test.py < test2.html
None

有人知道为什么第二个找不到吗?

最佳答案

当按名称和文本搜索元素时,BeautifulSoup 会检查 .string的元素以匹配所需的文本。这种令人困惑的行为实际上包含在 documentation 中。 :

If you pass one of the find* methods both string and a tag-specific argument like name, Beautiful Soup will search for tags that match your tag-specific criteria and whose Tag.string matches your value for string. It will not find the strings themselves. Previously, Beautiful Soup ignored the tag-specific arguments and looked for strings.

在第二种情况下,div 元素的 .stringNone - 这就是您没有得到任何结果的原因。相反,直接查找文本节点:

soup.find(text=re.compile(r"Scientific"))

而且,如果您需要实际的父元素,您可以从 .parent 中获取它:

soup.find(text=re.compile(r"Scientific")).parent

关于python - 如何使用BeautifulSoup匹配<div></div>中嵌入<a></a>的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com