beautifulsoup通過id獲取指定元素內容
阿新 • • 發佈:2019-02-06
<tr style="background-color:#fff;"> <td colspan="2" align=left valign="top"> <table id="zoom2" width="94%" border="0" cellspacing="0" cellpadding="0" style="margin:0 auto"> <!--startprint--> <tr> <th scope="col" id="DetailTilte"> <h1>微部落格資訊服務管理規定</h1> </th> </tr> <tr> <td scope="col" id="DetailContent">
比如有如上一段html程式碼,想要得到微部落格資訊服務管理規定這個字串
發現他有個id="DetailTitle"
於是可以通過beautifulsoup 的 find方法找到他
def get_title(url):
resp = urllib.request.urlopen(url)
html = resp.read()
bs = BeautifulSoup(html, "html.parser")
title = bs.find('th', id='DetailTilte').h1.get_text()
return title
定義一個python 的 get_title 方法
bs.find第一個引數表示標籤的名字,可以是'a' ,'p'之類,程式碼尋找的是a標籤或者是p標籤
後面跟一個屬性,可以是id,可以是name,或者其他的一些屬性,我這裡填寫了id='DetailTitle'
完了之後會得到
<th scope="col" id="DetailTilte"> <h1>微部落格資訊服務管理規定</h1> </th>
這樣一個字串,我們需要得到這個th標籤裡面的h1,所以把h1給提出來
bs.find('th', id='DetailTilte').h1
但是這樣仍然不夠乾淨,
<h1>微部落格資訊服務管理規定</h1>
會得到這樣一個字串, 我們不需要得到h1
再對他使用一個get_text方法得到他裡面的內容