html頁面如下
<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">
用法:
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
bs.find第一個參數表示標簽的名字,可以是'a' ,'p'之類,代碼尋找的是a標簽或者是p標簽
后面跟一個屬性,可以是id,可以是name,或者其他的一些屬性,我這里填寫了id='DetailTitle'
完了之后會得到
<th scope="col" id="DetailTilte">
<h1>微博客信息服務管理規定</h1>
</th>
這樣一個字符串,我們需要得到這個th標簽里面的h1,所以把h1給提出來,且獲取他的文案
h1.get_text()
原文鏈接:https://blog.csdn.net/lynn_coder/article/details/79509863