【问题标题】:Use BeautifulSoup to get a value after a specific tag使用 BeautifulSoup 获取特定标签后的值
【发布时间】:2014-11-04 20:50:17
【问题描述】:

我很难让 BeautifulSoup 为我抓取一些数据。从此代码示例中访问日期(实际数字,2008 年)的最佳方法是什么?这是我第一次使用 Beautifulsoup,我已经知道如何从页面上刮掉 url,但我不能把它缩小到只选择单词 Date,然后只返回后面的任何数字日期(在 dd括号)。我问的可能吗?

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

【问题讨论】:

  • 显示您尝试过的内容?
  • 我尝试过以各种方式使用soup.find_all,还有soup.select("dt"),它获取所有标签,但我想要它们在dd括号中的标签,但如果没有标签,如果我 soup.select("dd"),我会得到大量我不想要的值,我只想要特定于我正在寻找的标签的值。

标签: python web-scraping beautifulsoup html-parsing


【解决方案1】:

找到dt标签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())

打印2008

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多