通过id获取指定元素内容

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

猜你喜欢

转载自www.cnblogs.com/kaibindirver/p/11355504.html