使用BeautifulSoup获取特定标签后的值

2023-11-26

我很难让 BeautifulSoup 为我抓取一些数据。从此代码示例中访问日期(实际数字,2008 年)的最佳方法是什么?这是我第一次使用 Beautifulsoup,我已经弄清楚如何从页面上刮掉 url,但我无法完全缩小范围以仅选择单词“日期”,然后仅返回后面的任何数字日期(在 dd 中)括号)。我所问的可能吗?

<div class='dl_item_container clearfix detail_date'>
    <dt>Date</dt>
    <dd>
        2008
    </dd>
</div>

找出dt tag by text并找到next dd sibling:

soup.find('div', class_='detail_date').find('dt', text='Date').find_next_sibling('dd').text

完整代码:

from bs4 import BeautifulSoup

data = """
<div class='dl_item_container clearfix detail_date'>
    <dt>Date</dt>
    <dd>
    2008
    </dd>
</div>
"""

soup = BeautifulSoup(data, 'html.parser')
date_field = soup.find('div', class_='detail_date').find('dt', text='Date')
print(date_field.find_next_sibling('dd').text.strip())

Prints 2008.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用BeautifulSoup获取特定标签后的值 的相关文章

随机推荐