python爬虫BeautifulSoup模块解析数据入门

40 阅读4分钟
The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were

Elsie,

Lacie and

Tillie;

and they lived at the bottom of a well.

"""

2.基本方法

============================================================================

首先需要用BeautifulSoup() 方法传递一个解析器

soup = BeautifulSoup(html_doc, 'lxml')

print(soup) # 查看

在这里插入图片描述

prettify() 方法 格式化输出:

print(soup.prettify()) # 代码的格式化

在这里插入图片描述

获取指定标签(只获取第一个匹配的)

print(soup.title)

在这里插入图片描述

获取指定标签的标签名

print(soup.title.name)

在这里插入图片描述

获取指定标签的文本字符串

print(soup.title.string)

在这里插入图片描述

使用**find()**方法,获取指定标签(只获取第一个与之匹配的)

print(soup.find('p'))

在这里插入图片描述

使用 find_all() 方法,获取全部与之匹配的标签,结果放在一个列表中

print(soup.find_all('a'))

在这里插入图片描述

找多个标签,给find_all()传入一个标签列表

print(soup.find_all(['a', 'p']))

在这里插入图片描述

get() 方法 获取标签的属性

links = soup.find_all('a') # 'a'通过字符串传递字符串过滤器

for link in links:

print(link.get('href'))

在这里插入图片描述

attrs 属性 获取标签的全部属性

links = soup.find_all('a')

a = links[0]

print(a.attrs)

在这里插入图片描述

3.对象种类

============================================================================

soup = BeautifulSoup(html_doc, 'lxml')

print(type(soup.title))

print(type(soup.p))

print(type(soup.a))

print(type(soup.find('a')))

在这里插入图片描述

得到的都是Tag标签类型,不是字符串。


title_head = soup.head

print(type(title_head.string))

在这里插入图片描述

可导航的字符串(可操纵的字符串)


print(type(soup)) # bs对象

在这里插入图片描述

bs对象。


此外,还有注释类型,指的是html文件的注释标签部分,形如

<!–xxxxxxxxx–>

这里不再具体展示,了解即可。

收集整理了一份《2024年最新Python全套学习资料》免费送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。 img img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Python知识点,真正体系化!

了解详情:docs.qq.com/doc/DSnl3ZG…