BeautifulSoup

阅读目录

一 什么是BeautifulSoup

  简单来讲,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。html

官方解释以下:

  Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,经过解析文档为用户提供须要抓取的数据,由于简单,因此不须要多少代码就能够写出一个完整的应用程序。html5

  Beautiful Soup 是一个能够从HTML或XML文件中提取数据的Python库。它可以经过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。因此须要配合解析器一块儿使用python

  Beautiful Soup会帮你节省数小时甚至数天的工做时间.你可能在寻找 Beautiful Soup3 的文档,Beautiful Soup 3 目前已经中止开发,官网推荐在如今的项目中使用Beautiful Soup 4。浏览器

 

解析器:

  Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,若是咱们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更增强大,速度更快,推荐安装另外一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同。cookie

解析器对比:   官方文档ide

# 安装 Beautiful Soup

    pip3 install beautifulsoup4

#安装解析器
'''
    Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操做系统不一样,能够选择下列方法来安装lxml:

        apt-get install Python-lxml  

        pip3 install lxml  


    另外一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,能够选择下列方法来安装html5lib:

      apt-get install Python-html5lib 

      pip3 install html5lib 
'''
View Code

 

二 为何要用BeautifulSoup?

  BeautifulSoup能给咱们提供一些列查找文档树的方法,使咱们能快速定位到咱们想要爬取的数据。咱们再回想一下以前学的一个re模块,它能够全局查找咱们想要的文本,从文本开头到结束开始匹配,而后经过贪婪匹配,再经过非贪婪匹配拿到须要的数据,整个过程是否是很是繁琐,而却搜索效率极低!函数

  BeautifulSoup内既封装了re,还为咱们提供了一些更增强大、高效的功能,使咱们能够快速匹配到咱们想要的数据,提升爬取效率和开发效率。工具

三 安装

一、安装

# 安装BeautifulSoup4
pip3 install beautifulsoup4 # 安装解析器
# 根据官网解释,推荐使用lxml
pip3 install lxml

 

 四  怎么使用

一、基本使用

注意: 如何初始文本内有换行,也会算在里面。(坑)
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>

<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
"""

from bs4 import BeautifulSoup

# 第一个参数是解析文本
# 第二个参数是解析器
soup = BeautifulSoup(html_doc, 'lxml')

# 具有自动补全html标签功能
print(soup)

# 美化html便签
html_doc = soup.prettify()
print(html_doc)

 

二、遍历文档树

'''
    一、直接使用
    二、获取标签的名称
    三、获取标签的属性
    四、获取标签的内容
    五、嵌套选择
    六、子节点、子孙节点
    七、父节点、祖先节点
    八、兄弟节点
'''
from bs4 import BeautifulSoup

# 注意: 如何初始文本内有换行,也会算在里面。(坑)
html_doc = """
<html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" >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>
"""


# 第一个参数是解析文本
# 第二个参数是解析器
soup = BeautifulSoup(html_doc, 'lxml')

# 具有自动补全html标签功能
# print(soup)

# 美化html便签
html_doc = soup.prettify()
# print(html_doc)
# soup = BeautifulSoup(html_doc, 'lxml')


# 一、直接选择标签(返回的是一个对象)
print(soup.a)  # 获取第一个a标签
print(soup.p)  # 获取第一个p标签
print(type(soup.a))  # <class 'bs4.element.Tag'>

# 二、获取标签的名称
print(soup.a.name)  # 获取a标签的名字

# 三、获取标签的属性
print(soup.a.attrs)  # 获取a标签内全部的属性

# 四、获取标签的内容
print(soup.a.attrs['href'])  # 获取a标签内的href属性

# 五、嵌套选择标签
print(soup.p.b)  # 获取第一个p标签内的b标签
print(soup.p.b.text)  # 打印b标签内的文本

# 六、子节点、子孙节点
# 获取子节点
print(soup.p.children)  # 获取第一个p标签全部的子节点,返回的是一个迭代器
print(list(soup.p.children))  # list转成列表

# 获取子孙节点
print(soup.body.descendants)  # 获取body标签内全部的子孙节点,返回的是一个生成器
print(list(soup.body.descendants))  # list转成列表

# 获取第一个p标签中全部的内容,返回的是一个列表
print(soup.p.contents)

# 七、父节点、祖先节点
# 获取父节点
print(soup.a.parent)  # 获取第一个a标签内的父节点

# 获取祖先节点(爸爸,爸爸的爸爸,爸爸的爸爸的爸爸...以此类推)
print(list(soup.a.parents))  # 获取第一个a标签的祖先节点,返回的是一个生成器

print('*' * 1000)
# 八、兄弟节点  (sibling: 兄弟姐妹)
print(soup.a)
# 获取下一个兄弟节点
print(soup.a.next_sibling)
# 获取下一个的全部兄弟节点,返回的是一个生成器
print(soup.a.next_siblings)
print(list(soup.a.next_siblings))

# 获取上一个兄弟节点
print(soup.a.previous_sibling)
# 获取上一个的全部兄弟节点,返回的是一个生成器
print(list(soup.a.previous_siblings))
View Code

 

三、搜索文档树

  BeautifulSoup定义了不少搜索方法,这里着重介绍2个:find() find_all() 。其它方法的参数和用法相似!post

'''
标签查找与属性查找:

    标签:
        - 字符串过滤器   字符串全局匹配
            name 属性匹配
            attrs 属性查找匹配
            text 文本匹配
    
        - 正则过滤器
            re模块匹配
    
        - 列表过滤器
            列表内的数据匹配
    
        - bool过滤器
            True匹配
    
        - 方法过滤器
            用于一些要的属性以及不须要的属性查找。
        
    属性:
        - class_
        - id
'''
from bs4 import BeautifulSoup
import re

# 注意: 如何初始文本内有换行,也会算在里面。(坑)
html_doc = """
<html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" >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>
"""


# 第一个参数是解析文本
# 第二个参数是解析器
soup = BeautifulSoup(html_doc, 'lxml')

'''
标签查找与属性查找:

    标签:
        - 字符串过滤器   字符串全局匹配
            name 属性匹配
            attrs 属性查找匹配
            text 文本匹配
    
        - 正则过滤器
            re模块匹配
    
        - 列表过滤器
            列表内的数据匹配
    
        - bool过滤器
            True匹配
    
        - 方法过滤器
            用于一些要的属性以及不须要的属性查找。
        
    属性:
        - class_
        - id
'''


# 一、字符串
# find的默认参数 第一个是name、第二个是attrs、第四个是text
# name: 根据标签名匹配节点
print(soup.find('p'))  # 获取第一个p标签
print(soup.find_all(name='p'))  # 获取全部的p标签

# attrs: 根据属性查找匹配节点
print(soup.find(attrs={'id': 'p'}))  # 查找id为p的标签
print(soup.find_all(attrs={'class': 'sister'}))  # 查找class为sister的全部标签

# text: 根据文本匹配文档树内的文本
# 推荐配合其余匹配规则使用,不然毫无心义
print(soup.find(text='$37'))  # 查找标签内为$37的文本

# name与text配合使用
print(soup.find_all(name='p', text='$37'))  # 查找全部文本为$37的p标签

# name与attrs配合使用
print(soup.find(name='a', attrs={'id': 'link2'}))  # 查找第一个id为link2的a标签

# attrs与text配合使用
print(soup.find_all(attrs={'id': 'link2'}, text='Lacie'))  # 查找全部id为link2,文本为Lacie的标签

# name、attrs、text组合使用
print(soup.find_all(name='a', attrs={'id': 'link3'}, text='Tillie'))  # 查找全部id为link3,文本为Tillie的a标签


# 二、正则
print(soup.find(name=re.compile('a')))  # 经过第一个标签名带有a的节点
print(soup.find_all(attrs={'id': re.compile('link')}))  # 匹配全部id名带有link的节点
print(soup.find_all(text=re.compile('and')))  # 匹配全部文本带有"and"的节点


# 三、列表 (列表内能够匹配多个)
print(soup.find_all(name=['a', re.compile('e')]))  # 匹配全部a标签节点与全部标签中带有e的节点
print(soup.find_all(text=['$']))  # 找不到,由于$是精确查找
print(soup.find_all(text=['$37']))  # 查找$37文本,这样查找是没有意义的
print(soup.find_all(text=[re.compile('\$')]))  # 正则中$是特殊字符,因此须要转义


# 四、bool
print(soup.find_all(name=True))  # 查找全部有标签名的节点
print(soup.find_all(attrs={'id': True}))  # 查找全部有id的节点
print(soup.find_all(text=True))  # 查找全部文本


# 五、方法
# 写一个只要有class没有id的a标签的函数
def has_class_not_id(arg):
    if arg.name == 'a' and arg.has_attr('class') and not arg.has_attr('id'):
        return arg.name

print(soup.find_all(name=has_class_not_id))  # 经过has_class_not_id的函数匹配节点


# 六、标签与属性查找
# 标签
print(soup.find_all(attrs={'class': 'sister'}))

# 属性
# 根据class属性查找,由于class是关键字,因此后面须要加下划线
print(soup.find_all(class_='sister'))
# 根据id属性查找
print(soup.find_all(id='link2'))
View Code

修改文档树 url

五 自动登陆抽屉新热榜并点赞与评论

'''
# 抽屉新热榜自动登录并点赞
    1.须要携带评论主页的cookies信息去进行点赞,不然点赞失败

'''
from bs4 import BeautifulSoup
import requests
# 经过bs4解析库获取全部新闻的id
for line in range(2, 4):
    index_url = 'https://dig.chouti.com/all/hot/recent/{0}'.format(line)
    response1 = requests.get(index_url,
                            headers={
                                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
                            }
                            )

    response1_cookies = response1.cookies

    soup = BeautifulSoup(response1.text, 'html.parser')

    items = soup.find_all(attrs={'class': 'item'})
    # print(items)

    for item in items:
        div_tag = item.find(attrs={'class': 'part2'})
        # print(div)
        # print(type(div))
        # 拿到全部的id
        user_id = div_tag.get('share-linkid')
        # print(user_id)

        form_data = {
            "phone": "8615622792660",
            "password": "kermit46709394",
            "oneMonth": '1'
        }

        # print(url)
        response2 = requests.post('https://dig.chouti.com/login',
                                  headers={
                                      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
                                  },
                                  data=form_data,
                                  cookies=response1_cookies
                                  )

        url = 'https://dig.chouti.com/link/vote?linksId={user_id}'.format(user_id=user_id)

        # 抽屉新热榜自动点赞
        response3 = requests.post(url,
                                  headers={
                                      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
                                  },
                                  cookies=response1_cookies
                                  )


        print(response3.text)
View Code
相关文章
相关标签/搜索