<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方法得到他裏面的內容