BeautifulSoup支持最常用的CSS selectors,这是将字符串转化为Tag对象或者BeautifulSoup自身的.select()方法。

本篇所使用的html为:

html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" 

举例,你可以这样搜索便签

soup.select("title")   #使用select函数# [<title>The Dormouse's story</title>]soup.select("p nth-of-type(3)")# [<p>...</p>]

另外,你也可以搜索在其他父标签内部的标签,即通过标签的所属关系寻找标签

soup.select("body a")   #搜索在body标签内部的a标签# [<a class="sister" href="http://example.com/elsie" )  #搜索在html->head标签内部的标签# [<title>The Dormouse's story</title>]

可以直接寻找在其他标签内部的标签

soup.select("head > title")# [<title>The Dormouse's story</title>]soup.select("p > a")# [<a class="sister" href="http://example.com/elsie" )# []

通过tags标签获得元素的同胞兄弟

soup.select("#link1 ~ .sister")  #获得id为link1,class为sister的兄弟标签内容(所有的兄弟便签)# [<a class="sister" href="http://example.com/lacie" >Lacie</a>]

通过CSS的类获得tags标签:

soup.select(".sister") #获得所有class为sister的标签# [<a class="sister" href="http://example.com/elsie" >Tillie</a>]

通过id获得标签:

soup.select("#link1") #通过设置参数为id来获取该id对应的tag# [<a class="sister" href="http://example.com/elsie" >Lacie</a>]

通过设置select函数的参数为列表,来获取tags。只要匹配列表中的任意一个则就可以捕获。

soup.select(“#link1,#link2”) #捕获id为link1或link2的标签# [<a class=”sister” href=”http://example.com/elsie” id=”link1”>Elsie</a>, # <a class=”sister” href=”http://example.com/lacie” id=”link2”>Lacie</a>]

按照标签是否存在某个属性来获取:

soup.select('a[href]') #获取a标签中具有href属性的标签# [<a class="sister" href="http://example.com/elsie" >Tillie</a>]

通过某个标签的具体某个属性值来查找tags:

soup.select('a[href="http://example.com/elsie"]')# [<a class="sister" href="http://example.com/elsie" >Elsie</a>]

这里需要解释一下:
soup.select(‘a[href^=”http://example.com/”]’) 意思是查找href属性值是以”http://example.com/“值为开头的标签,可以查看博客介绍。
soup.select(‘a[href$=”tillie”]’) 意思是查找href属性值是以tillie为结尾的标签。
soup.select(‘a[href*=”.com/el”]’) 意思是查找href属性值中存在字符串”.com/el”的标签,所以只有href=”http://example.com/elsie”一个匹配。

如何查询符合查询条件的第一个标签:

soup.select_one(".sister") #只查询符合条件的第一个tag# <a class="sister" href="http://example.com/elsie" >Elsie</a>

相关文章:

  • 2022-12-23
  • 2021-11-04
  • 2021-11-04
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-11-04
猜你喜欢
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
  • 2021-08-10
  • 2021-11-04
  • 2021-11-04
  • 2021-11-04
相关资源
相似解决方案