2014-09-11 76 views
5

我很難讓BeautifulSoup爲我刮取一些數據。從此代碼示例訪問日期的最佳方式(實際數字,2008)是什麼?這是我第一次使用Beautifulsoup,我已經想出瞭如何從網頁上刮掉網頁,但是我無法將其縮小到只選擇Date這個詞,然後只返回任何數字日期(在dd中括號)。我甚至可能問什麼?使用BeautifulSoup獲得特定標記後的值

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

顯示你試過的東西? – fledgling 2014-09-11 03:09:33

+0

我嘗試過以各種方式使用soup.find_all,也是soup.select(「dt」),它獲取所有標籤,但我想要它們在dd括號中標記的內容,但沒有標籤,如果我soup.select(「dd」),我得到了一大堆我不想要的值,我只想要特定於我正在尋找的標籤的值。 – knames 2014-09-11 03:14:04

回答

11

找到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) 
date_field = soup.find('div', class_='detail_date').find('dt', text='Date') 
print date_field.find_next_sibling('dd').text.strip() 

打印2008

相關問題