Beautiful Soup - 通过属性查找元素



find() 和 find_all() 方法都用于根据传递给这些方法的参数查找文档中一个或所有标签。您可以将 attrs 参数传递给这些函数。attrs 的值必须是一个字典,其中包含一个或多个标签属性及其值。

为了检查这些方法的行为,我们将使用以下HTML文档 (index.html)

<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <form>
         <input type = 'text' id = 'nm' name = 'name'>
         <input type = 'text' id = 'age' name = 'age'>
         <input type = 'text' id = 'marks' name = 'marks'>
      </form>
   </body>
</html>

使用 find_all()

以下程序返回所有具有 input type="text" 属性的标签列表。

示例

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

obj = soup.find_all(attrs={"type":'text'})
print (obj)

输出

[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]

使用 find()

find() 方法返回已解析文档中第一个具有给定属性的标签。

obj = soup.find(attrs={"name":'marks'})

使用 select()

select() 方法可以通过传递要比较的属性来调用。属性必须放在列表对象中。它返回所有具有给定属性的标签列表。

在以下代码中,select() 方法返回所有具有 type 属性的标签。

示例

from bs4 import BeautifulSoup

fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

obj = soup.select("[type]")
print (obj)

输出

[<input id="nm" name="name" type="text"/>, <input id="age" name="age" type="text"/>, <input id="marks" name="marks" type="text"/>]

使用 select_one()

select_one() 方法与此类似,只是它返回满足给定过滤器的第一个标签。

obj = soup.select_one("[name='marks']")

输出

<input id="marks" name="marks" type="text"/>
广告
© . All rights reserved.