soup.select()函数的使用用法 | 您所在的位置:网站首页 › beautifulsoup的select方法层级查找 › soup.select()函数的使用用法 |
soup.select()在源代码中的原型为: select(self, selector, namespaces=None, limit=None, **kwargs)功能:查找html中我们所需要的内容 我们主要使用的参数是selector,其定义为”包含CSS选择器的字符串“。关于CCS,也需要了解一些概念,参考CCS语法与CSS Id 和 Class。 我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select()。如下代码(如h1,p等为标签.center为类名,#para1为id): 菜鸟教程(runoob.com) .center { text-align:center; } #para1 { text-align:center; color:red; } 标题居中 红色段落居中。以下是将要用到的代码 from bs4 import BeautifulSoup html = """ The Dormouse's storyThe Dormouse's story Once upon a time there were three little sisters; and their names were , Lacie and Tillie ; and they lived at the bottom of a well. ... """ soup = BeautifulSoup(html, 'lxml') # 传入解析器:lxmlsoup.select()可通过以下方法进行查找。 1.通过(HTML)标签名查找 print(soup.select('title')) print(soup.select('a'))#输出的列表含有多个包含标签的元素输出为: [The Dormouse's story] [, Lacie, Tillie] 2.通过CCS类选择器查找 print(soup.select('.story'))输出为 [Once upon a time there were three little sisters; and their names were , Lacie and Tillie; and they lived at the bottom of a well., ...] 3.通过CCS id 选择器查找 print(soup.select('#link1'))输出为: [] 4.组合查找组合查找和通过标签名与类选择器、id选择器进行查找的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开。 print(soup.select('p #link1'))输出为: [] 5.子标签查找父标签与子标签之间通过" > "表示递进关系 print(soup.select('p > b'))输出为: [The Dormouse's story]通过子标签查找时的注意事项:soup.select()尽量不使用完整selector 6.通过属性查找还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。 # 通过href属性及其值进行查找 print(soup.select('a[href="http://example.com/elsie"]'))输出为: [] |
CopyRight 2018-2019 实验室设备网 版权所有 |