探索 BeautifulSoap 方法

原文:https://www.studytonight.com/python/web-scraping/exploring-beautifulsoup-methods

在本教程中,我们将学习各种不同的方法来访问 HTML 标签使用不同的方法的美丽的输出模块。要获得关于美丽的输出模块的基本介绍,请从之前的教程开始。


BeautifulSoap:访问 HTML 标签

我们将在本节中介绍的方法用于遍历不同的 HTML 标记,将 HTML 代码视为一棵树。

创建一个文件sample _ 网页. html 并在其中复制以下 html 代码:

<!DOCTYPE html>
<html>

    <head>
        <title> Sample HTML Page</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            div {
                width: 95%;
                height: 75px;
                margin: 10px 2.5%;
                border: 1px dotted grey;
                text-align: center;
            }

            p {
                font-family: sans-serif;
                font-size: 18px;
                color: #000;
                line-height: 75px;
            }

            a {
                position: relative;
                top: 25px;
            }
        </style>
    </head>

    <body>
        <div id="first-div">
            <p class="first">First Paragraph</p>
        </div>

        <div id="second-div">
            <p class="second">Second Paragraph</p>
        </div>

        <div id="third-div">
            <a href="https://www.studytonight.com">Studytonight</a>
            <p class="third">Third Paragraph</p>        
        </div>

        <div id="fourth-div">
            <p class="fourth">Fourth Paragraph</p>        
        </div>

        <div id="fifth-div">
            <p class="fifth">Fifth Paragraph</p>        
        </div>
    </body>
</html>

现在要读取上述 HTML 文件的内容,使用下面的 python 代码将内容存储到一个变量中:

## reading content from the file
with open("sample_webpage.html") as html_file:
    html = html_file.read()

现在,我们将使用不同方法的美丽组模块,看看它们是如何工作的。

预热,先用prettify方法。

import bs4

## reading content from the file
with open("sample_webpage.html") as html_file:
    html = html_file.read()

## creating a BeautifulSoup object
soup = bs4.BeautifulSoup(html, "html.parser")

print(soup.prettify)
示例 HTML 页面

第一段

第二段

StudyTonight

第三段

第四段

第五段


BeautifulSoap:访问 HTML 标签属性

我们可以使用以下语法检索任何 HTML 标记的属性:

TagName["AttributeName"]

让我们从 HTML 代码中的锚点标签中提取href属性。

import bs4

## reading content from the file
with open("sample_webpage.html") as html_file:
    html = html_file.read()

## creating a BeautifulSoup object
soup = bs4.BeautifulSoup(html, "html.parser")

## getting anchor tag
link = soup.a

## printing the 'href' attribute of anchor tag
print(link["href"])

https://www.studytonight.com


美丽组:contents方法

contents方法用于列出父标签中存在的所有标签。让我们使用contents方法列出正文标签的所有子 HTML 标签。

body = soup.body

## getting all the children of 'body' using 'contents'
content_list = body.contents

## printing all the children using for loop
for tag in content_list:
    if tag != "\n":
        print(tag)
        print("\n")

第一段

第二段

StudyTonight

第三段

第四段

第五段


美丽组:children方法

children方法类似于contents方法,但是children方法返回一个迭代器,而contents方法返回一个所有子代的列表。让我们看一个例子:

body = soup.body

## we can also convert iterator into list using the 'list(iterator)'
for tag in body.children:
    if tag != "\n":
        print(tag)
        print("\n")

第一段

第二段

StudyTonight

第三段

第四段

第五段


美丽组:descendants方法

descendants方法有助于检索父标签的所有子标签。你一定想知道上面两个方法也是这么做的。这个方法不同于contentschildren方法,因为这个方法提取所有的子标签和内容直到最后。简单来说,如果我们用它来提取身体标签,那么它将打印第一个 div 标签,然后它将打印 div 标签的子标签,然后他们的子标签,直到它到达终点,然后它将继续下一个 div 标签,以此类推。

该方法返回一个发生器。让我们看一个例子:

body = soup.body

## getting child tags of 'body' tag using 'descendants' method
for tag in body.descendants:
    if tag != "\n":
        print(tag)
        print("\n")

第一段

第一段

第一段

第二段

第二段

第二段StudyTonight

第三段

T18】StudyTonightStudyTonight

第三段

第三段

第四段

T26】第四段第四段 T29

正如您在上面的输出中看到的那样,descendants方法一直进入它读取的标签内部,直到它到达末尾,然后它移动到下一个 HTML 标签上。


美丽组:parent方法

parent方法用于获取子标签的父标签。让我们看一个例子:

body = soup.body

## getting parent of 'body'
body_parent = body.parent

## you have to use 'name' method to print the name of the tag
## printing the name of the parent using 'name' method
print(body_parent.name)

超文本标记语言


美丽组:parents方法

parent方法用于获取一个子标签的所有父标签。它返回一个发电机。让我们看一个例子:

body = soup.body

## getting parents of 'body'
body_parents = body.parents

## if the child has more than one parent it will print all parent names
for parent in body_parents:
    print(parent.name)
    print("\n")

html[文档]


美丽组:next_sibling方法

next_sibling方法用于从同一个父标签获取指定标签的下一个标签。现在让我们在输出的 HTML 代码中打印锚点标签的同级标签:

anchor_tag = soup.a

print(anchor_tag)

## getting third paragraph using anchor tag
## here we have written 'next_sibling' two times 
## means there is a line break in between them
## anchor_tag.next_sibling gives a line break
## next to line break is the third paragraph
third_para = anchor_tag.next_sibling.next_sibling

print(third_para)

StudyTonightT2】第三段


美丽组:previous_sibling方法

previous_sibling方法类似于next_sibling方法。它返回上一个标签,而不是下一个标签。让我们看一个例子(这是上面代码片段的延续):

## getting anchor tag from the third_para
print(third_para.previous_sibling.previous_sibling)

StudyTonight


美丽组:next_siblings方法

next_siblings返回带有所有可用下一个标签的生成器。让我们看一个例子(这是上面代码片段的延续):

## using anchor_tag variable here
a_siblings = anchor_tag.next_siblings

print(list(a_siblings))

['\n ',

第三段

,' \n']


美丽组:previous_siblings方法

previous_siblings返回一个带有所有可用先前标签的生成器。让我们看一个例子(这是上面代码片段的延续):

## using third_para variable here
p_siblings = third_para.previous_siblings

print(list(p_siblings))

['\n ',lt;a href = " https://www . study now . com " > study now,' \n']

现在,您已经熟悉了大多数用于网页抓取的方法。在下面的教程中,我们将学习如何从一堆相似的标签中找到一个特定的标签。