爬虫学习笔记(九)数据解析——bs4 2020.5.8

前言

本节学习数据解析的beautiful soup
在这里插入图片描述

1、基本使用

安装

pip install beautifulsoup4

简单调用解析库

from bs4 import BeautifulSoup
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>
"""
# 1.转类型
# 默认bs4会 调用你系统中lxml的解析库 警告提示
# 主动设置 bs4的解析库
soup = BeautifulSoup(html_doc, 'lxml')
# 2.格式化输出 补全
result = soup.prettify()
print(result)

2、四大对象

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="story"><!--...--></p> #注释
<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>
"""
# 1.转类型 bs4.BeautifulSoup'
soup = BeautifulSoup(html_doc, 'lxml')
print(type(soup))
# 2. 解析数据
# Tag 标签对象 bs4.element.Tag'
result = soup.head
# 注释的内容  类型 'bs4.element.Comment'
result = soup.p.string
print(type(result))
print(result)
result = soup.a
print(result)
# 内容 Navigablestring  'bs4.element.NavigableString
result = soup.a.string
print(result)
# 属性
result = soup.a['href']
print(result)

这些都只能取第一个

3、多点解析

from bs4 import BeautifulSoup
html_doc = """
<html><head>
<title id="one">The Dormouse's story</title>
</head>
<body>
<p class="story"><!--...--></p>
<p class="title">
    p标签的内容
    <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>
"""
# 1.转类型 bs4.BeautifulSoup'
soup = BeautifulSoup(html_doc, 'lxml')
# 2.通用解析方法
#  find--返回符合查询条件的 第一个标签对象
result = soup.find(name="p")
print(result) #打印了第一个p
result = soup.find(attrs={"class": "sisiter"})
print(result) #打印第一个class="sister"
result = soup.find(text="Tillie")
print(result) #这个没意思,写什么传什么
result = soup.find(
    name='p',
    attrs={"class": "story"},
)
print(result) 
# find_all--list(标签对象)
result = soup.find_all('a')
print(result) #返回列表
result = soup.find_all("a", limit=1)[0]
print(result) #就是find源码
result = soup.find_all(attrs={"class": "sister"})
print(result) #所有class="sister"
# select_one---css选择器
result = soup.select_one('.sister')
print(result) 
# select----css选择器---list
result = soup.select('.sister')
print(result) #类选择器
result = soup.select('#one')
print(result) #ID选择器
result = soup.select('head title')
print(result) #后带选择器
result = soup.select('title,.title')
print(result) #主选择器
result = soup.select('a[id="link3"]')
print(result) #属性选择器
# 标签包裹的内容---list
result = soup.select('.title')[0].get_text()
print(result)
# 标签的属性
result = soup.select('#link1')[0].get('href')
print(result)

4、例子

import requests
from bs4 import BeautifulSoup
from lxml import etree
import json
class BtcSpider(object):
    def __init__(self):
        self.url = 'http://8btc.com/forum-61-{}.html' #要翻页,用个大括号
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
            }
        # 保存列表页的数据
        self.data_list = []
        self.data_detail = []
    # 1.发请求
    def get_response(self, url):
        response = requests.get(url, headers=self.headers)
        data = response.content #这里转字符串的话会出问题
        return data
    # 2.解析数据list
    def parse_list_data(self, data):
        # 1.转类型
        soup = BeautifulSoup(data, 'lxml')
        # 2.解析内容 取出 所有的类选择器的 A
        """
        html_data = etree.HTML(data)
        result_list = html_data.xpath('//div[contains(@id,"stickthread")]') #模糊查询
        result_list = html_data.xpath('//head/following-sibling::*[1]') #取下一个标签(平级)
        print(len(result_list))
        print(result_list)
        """
        title_list = soup.select('.xst')
        for title in title_list:
            list_dict_data = {}
            list_dict_data['title'] = title.get_text()
            list_dict_data['detail_url'] = title.get('href')
            self.data_list.append(list_dict_data)
    # 3.解析数据详情页
    def parse_detail_data(self, data):
        html_data = BeautifulSoup(data, 'lxml')
        # 取出问题--list[1][0]
        question = html_data.select('#thread_subject')[0].get_text()
        print(question)
        answer_list = html_data.select('.t_f')
        for answer in answer_list:
            answer_list = []
            answer_list.append(answer.get_text())
        detail_data = {
            "question": question,
            "answer": answer_list
        }
        self.data_detail.append(detail_data)
    # 4.保存数据
    def save_data(self, data, file_path):
        data_str = json.dumps(data)
        with open(file_path, 'w') as f:
            f.write(data_str)
    # 5.启动
    def start(self):
        # 列表页的请求
        for i in range(1, 2):
            url = self.url.format(1)
            data = self.get_response(url)
            self.parse_list_data(data)
        self.save_data(self.data_list, "04list.json")
        # 发送详情页的请求
        for data in self.data_list:
            detail_url = data['detail_url']
            detail_data = self.get_response(detail_url)
            # 解析详情页的数据
            self.parse_detail_data(detail_data)
        self.save_data(self.data_detail, 'detail.json')
BtcSpider().start()

结语

bs4就是找选择器,比前两个要简单点
但效率还是正则快

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章