使用BeautifulSoup在特定标签后获取值
问题内容:
我很难让BeautifulSoup为我抓取一些数据。从此代码示例访问日期(实际数字,2008)的最佳方法是什么?这是我第一次使用Beautifulsoup,我已经弄清楚了如何从页面上抓取url,但是我不能完全缩小范围以仅选择单词Date,然后仅返回后面的数字日期(在dd中括号)。我要问的甚至可能吗?
<div class='dl_item_container clearfix detail_date'>
<dt>Date</dt>
<dd>
2008
</dd>
</div>
问题答案:
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)
date_field = soup.find('div', class_='detail_date').find('dt', text='Date')
print date_field.find_next_sibling('dd').text.strip()
印刷品2008
。