美文网首页
BeautifulSoup用法

BeautifulSoup用法

作者: 温小八 | 来源:发表于2018-10-30 23:08 被阅读0次

Beautiful的教程可以参考崔大神的这篇:https://cuiqingcai.com/1319.html

相关文档可以参考这个:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

以下是自己的练习

from bs4 import BeautifulSoup
import re



html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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初始化时,最好指定解析内库"lxml",不然会有警告,
# 而且不加上的话,系统会自动采取最高效的库进行解析,可能不同的系统解析不一致
soup = BeautifulSoup(html_doc, "lxml")

# 按照标准的缩进格式的结构输出
print(soup.prettify())


# ********* Tag对象 *********
print(soup.title)
# <title>The Dormouse's story</title>

print(soup.title.name)
# title

print(soup.title.parent.name)
# head

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

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

print(soup.p.attrs)
# {'name': 'dromouse', 'class': ['title']}
# 注意:一个标签可以有多个class属性,所以class是个list
print(soup.p['class'])
# ['title']
print(soup.p.get('class'))

# ********* NavigableString对象 *********
#获取标签内部的文字
print(soup.title.string)
# The Dormouse's story
print(type(soup.title.string))
# <class 'bs4.element.NavigableString'>


# ********* BeautifulSoup对象 *********
# BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag
print(type(soup.name))
# <class 'str'>
print(soup.name)
# [document]
print(soup.attrs)
# {} 空字典

# ********* Comment对象 *********
print(soup.a)
print(type(soup.a)) # <class 'bs4.element.Tag'>
print(soup.a.string)
print(type(soup.a.string))  # <class 'bs4.element.Comment'>


# 搜索find_all( name , attrs , recursive , text , **kwargs )
# name 参数可以查找所有名字为 name 的tag
# name为字符串时,Beautiful Soup会查找与字符串完整匹配的内容
# 查找文档中所有的<a>标签
print(soup.find_all('a'))
# name为正则表达式时,Beautiful Soup会通过正则表达式的 match() 来匹配内容
# 找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到
print(soup.find_all(re.compile('^b')))
# name为列表时,Beautiful Soup会将与列表中任一元素匹配的内容返回
# 找到文档中所有<a>标签和<b>标签
print(soup.find_all(["a", "b"]))

# find_all(id="xxx"):Beautiful Soup会搜索每个tag的”id”属性
print(soup.find_all(id="link2"))
# find_all(href="xxx"):Beautiful Soup会搜索每个tag的”href”属性
print(soup.find_all(href="http://example.com/lacie"))

# 使用多个指定名字的参数可以同时过滤tag的多个属性
# 想用 class 过滤,不过 class 是 python 的关键词,所以class_需要加个下划线
print(soup.find_all(class_="sister",id="link3"))


# CSS选择器
# 1.通过标签名查找
print(soup.select('head'))
print(soup.select('a'))

# 2.通过类名查找
print(soup.select('.sister'))

# 3.通过 id 名查找(通常建议使用id进行查找,id是唯一的
print(soup.select('#link2'))

# 4.组合查找
print(soup.select('p #link3'))
# 子标签查找
print(soup.select('p > b'))

# 5.属性查找
print(soup.select('a[class="sister"]'))
print(soup.select('p a[href="http://example.com/lacie"]'))

# select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容
for a in soup.select('a'):
    print(a.get_text())

CSDN示例:
注:相对于xpath的实现,这里只是改了parse_data()的内容

import requests
from bs4 import BeautifulSoup
import json
import time

# 爬取CSDN论坛信息的类
class BBSpider:
    url = "https://bbs.csdn.net/tech_hot_topics"
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

    # 存放最终的数据,用于数据存储
    result_list = []

    # 根据给到的url获取网页数据并返回
    def get_data(self, url):
        r = requests.get(url=url, headers=self.headers)
        data = r.text
        return data

    # 解析得到的网页数据,分析出该页的帖子的时间、帖子标题、帖子链接
    def parse_data(self, data, url):
        soup = BeautifulSoup(data, "lxml")
        div = soup.select(".list_1 > ul > li")
        for tiezi in div:
            dict = {}
            dict['time'] = tiezi.select('.time')[0].get_text()
            dict['title'] = tiezi.select('a')[0].get_text()
            dict['href'] = tiezi.select('a')[0].get('href')
            self.result_list.append(dict)
        print(len(self.result_list))



    # 存储数据,将result_list中的数据以json的格式保存到data.json文件中
    def save_data(self):
        data = json.dumps(self.result_list)
        with open("data.json", "w") as f:
            f.write(data)

    # 由于CSDN的论坛是以翻页的形式进行展示的,翻页的链接为:域名+"?page=xxx",以下是对每一页的数据进行数据的获取、解析,最后保存的操作
    def run(self):
        # 获取从第1页到第9页的数据
        for i in range(1,5):
            time.sleep(1)
            url = self.url + "?page="+str(i)
            data = self.get_data(url)
            self.parse_data(data, url)
        print(len(self.result_list))
        # 保存第1页到第9页全部的网页数据
        self.save_data()

# 对CSDN的论进行网页爬取
spider = BBSpider()
spider.run()

具体代码链接:https://github.com/zhuyecao/kaikeba/tree/master/kaikeba/beautifulsoup

相关文章

  • BeautifulSoup随笔

    Learn BeautifulSoup BeautifulSoup用法 引用崔庆才 静觅 基本语法及用法 初始化 ...

  • 2.2 再端一碗BeautifulSoup

    掌握BeautifulSoup的基本用法

  • 2019-02-24

    今天有朋友问到了BeautifulSoup的一个用法,于是我心血来潮,准备将BeautifulSoup的基本用法在...

  • BeautifulSoup用法

    Beautiful的教程可以参考崔大神的这篇:https://cuiqingcai.com/1319.html 相...

  • Python 爬虫基础教程——BeautifulSoup抓取入门

    大家好,上篇推文介绍了BeautifulSoup抓取的一些基础用法,本篇内容主要是介绍BeautifulSoup模...

  • 爬小说

    https://cuiqingcai.com/1319.html 这是BeautifulSoup的详细用法 创建s...

  • 课时9 解析网页中的元素

    Beautifulsoup 的中文文档,及里面find_all() 函数用法https://www.crummy....

  • Beautifulsoup的用法实例

    Beautifulsoup主要的功能是从网页抓取数据,相对于正则表达式来说,更简便,具体实例如下: 本文的主要目的...

  • BeautifulSoup库用法总结

    0.写在前面 在python的爬虫中,经常需要用到强大的beautifulsoup库,如之前写的股票数据的爬取中就...

  • 20160105| 1.2作业

    BeautifulSoup用法简说python split 拆分字符串python 判断变量类型为什么少用type...

网友评论

      本文标题:BeautifulSoup用法

      本文链接:https://www.haomeiwen.com/subject/dlzntqtx.html