beautifulsoup通过id获取指定元素内容

xiaoxiao2021-02-28  21

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

转载请注明原文地址: https://www.6miu.com/read-2150082.html

最新回复(0)