python爬虫-bs4基础

# 下面的一段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" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

# 使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:

from bs4 import BeautifulSoup

# soup = BeautifulSoup(html_doc)
# 如果BeautifulSoup(html_doc)就这样不做任何处理,回报一个 GuessedAtParserWarning 解析器警告
# 接着往下面看,添个解析器就好
soup = BeautifulSoup(html_doc, 'html.parser')

# print(soup.prettify())

#  几个简单的浏览结构化数据的方法:
print(soup.title)
# <title>The Dormouse's story</title>

print(soup.title.name)
# title

print(soup.title.string)
# The Dormouse's story

# 上一级标签名字
print(soup.title.parent.name)
# head

print(soup.p)
# <p class="title"><b>The Dormouse's story</b></p>

print(soup.p['class'])
# ['title']

print(soup.a)
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

print(soup.find_all('a'))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print(soup.find(id="link3"))
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

print(soup.find('<body>'))
posted @ 2023-02-28 20:16  0x1e61  阅读(9)  评论(0编辑  收藏  举报