在BeautifulSoup中,如何搜索包含文本但也有某个类的祖先的元素?

2024-09-30 23:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将beautifulsoup4与python3.7结合使用。我想找到一个元素,它的元素中有文本“points”,但也有一个类属性包含“article”的祖先DIV。我已经知道如何用文本搜索元素。。。你知道吗

points_elt = soup.find_all(text=re.compile(' points'))[0]

但是我不知道如何扩展上面的内容来包含文本中的元素,这些元素也包含类“article”的祖先。。你知道吗

<div class="article class2">
    ... other elements ...
    <span class="outerSpan">
        <span class="innerSpan">2000 points</span>
    </span>
   ... other element closing tags ...
</div>

这是另一个例子,它应该工作。。。你知道吗

<div class="article class7">
    <p>
        <div class="abc">
            <span class="outerSpan">
                <span>8000 points</span>
            </span>             
        </div>
    </p>
</div>

Tags: 文本div元素属性articlefindpointsclass
3条回答
from bs4 import BeautifulSoup
import re

data = """
<div class="article class2">
    <span class="outerSpan">
        <span class="innerSpan">2000 points</span>
    </span>
</div>
"""

soup = BeautifulSoup(data, 'html.parser')
for item in soup.findAll(text=re.compile('points$')):
    print(item)

输出:

2000 points
from bs4 import BeautifulSoup


data = """
<div class="article class2">
    <span class="outerSpan">
        <span class="innerSpan">2000 points</span>
    </span>
</div>
"""

soup = BeautifulSoup(data, 'html.parser')
for item in soup.findAll('span', {'class': 'innerSpan'}):
    print(item.text)

输出:

2000 points
span = soup.find_all('span')
if 'points' in span[1].text:
    div = span[1].parent.parent
    print(div)

span变量包含所有span元素,我们将遍历回HTML标记的父级。考虑到这总是HTML的格式。你知道吗

您可以使用css选择器并检查您正在处理的字符串。你知道吗

html='''<div class="article class2">
    <span class="outerSpan">
        <span class="innerSpan">2000 points</span>
    </span>
</div>
'''

soup=BeautifulSoup(html,'html.parser')
for item in soup.select('.article .innerSpan'):
   if 'points' in item.text:
       print(item.text)

或者你可以用这个。你知道吗

soup=BeautifulSoup(html,'html.parser')
for item in soup.select('.article:contains(points)'):
   print(item.text.strip())

相关问题 更多 >