Beautiful Soup

版权声明:个人博客网站:https://cunyu1943.github.io/, 欢迎访问留言交流! https://blog.csdn.net/github_39655029/article/details/84135595

定义

Python中的一个库,主要用于从网页爬取数据;

安装

pip install beautifulsoup4

四大对象

Beautiful Soup将复杂的HTML文档转换成树形结构,树中的每个节点都是Python对象,对象可归纳为以下4种;

Tag

XMLHTML中的标签tag相同,tag属性可被增删修改,操作方法和字典一样,最常用的属性如下;

  • name
  • attributes

NavigableString

获取标签之后,用于获取标签内部的文字;

BeautifulSoup

表示一个文档的全部内容,大多数情况下都可以将它当作Tag对象,是一个特殊的Tag对象,可用于分别获取其类型、名称及属性;

Comment

Comment是一个中枢类型的NavigableString对象,输出内容不含注释符号;

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time    : 2018-11-16 10:30
# @Author  : Manu
# @Site    : 
# @File    : beautiful_soup.py
# @Software: PyCharm

from bs4 import BeautifulSoup

html = """
<html>
<head>
<title>村雨</title>
</head>
<body>
<p class="title" name="blog"><b>村雨的博客</b></p>
<li><!--注释--></li>
<a href="https://blog.csdn.net/github_39655029/article/details/83933199" target="_blank">
        <span class="article-type type-1">
            原        </span>
        Python爬虫之网络请求      </a>

<a href="https://blog.csdn.net/github_39655029/article/details/84100458" target="_blank">
        <span class="article-type type-1">
            原        </span>
        爬虫实践--豆瓣电影当前上映电影信息爬取      </a>
        
</body>
</html>
"""
soup = BeautifulSoup(html, 'lxml')
print(soup.name)
print(soup.title.name)
print(soup.prettify())
# 获取title
print('title:', soup.title.text)
# 获取head
print('p:', soup.p.text)
a_list = soup.a.attrs
print(a_list.get('href'))

# 获取Title标签的文字内容
print(soup.title.string)

# 获取对象名称
print(soup.name)
# 获取对象属性
print(soup.attrs)
# 获取对象类型
print(type(soup.name))
if type(soup.li.string) == element.Comment:
    print('comment:', soup.li.string)

猜你喜欢

转载自blog.csdn.net/github_39655029/article/details/84135595