靓汤:获取没有特定类的特定文本

2024-10-03 17:20:08 发布

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

我试图得到下面突出显示的文本“frei ab 01.05.2017”。但问题是,“section_content iwüu right”类在该网站上存在了19次。我会做一个find_all并从那里只返回第11个元素,但是在一些我想抓取的站点上,这个类的数量是不同的,所以我可能不会总是找到正确的。有什么想法吗?谢谢!在

enter image description here


Tags: 文本right元素数量ab站点网站section
2条回答

您可以使用lxml,它比BeautifulSoup快一个数量级。在

下面的代码可以帮助您实现期望的结果。在

from lxml import html
html_string = """
    <div class="clear">
        <div class="section_content iw_right">
            <p>
            <span>
            </span>
            <strong>hello</strong>
            <br>
            <strong>gen</strong>
            </p>
        </div>
    </div>

    <div class="clear">
        <p>
        <span>
        </span>
        <strong>hello1</strong>
        <br>
        <strong>gen1</strong>
        </p>
    </div>
"""
root = html.fromstring(html_string)
r_xp = [elem.xpath('.//p/strong/text()')[0] for elem in root.xpath('//div[@class="clear"]')]
print(r_xp)

注意在示例html_string中,类为"section_content iw_right"的div从第二个div中消失。在

上述代码将导致:

^{pr2}$

获取所需元素的一种方法是使用前面的标签-找到带有“Erdgeschoss”文本和find the next ^{} siblingspan元素:

label = soup.find("span", text="Erdgeschoss")
print(label.find_next_sibling("strong").get_text())

相关问题 更多 >