天天看点

数据解析之BS4——实战

目录

​​一、bs4数据解析原理​​

​​1、环境安装​​

​​2、实例化一个BeautifulSoup对象,并且将页面源码数据加载到该对象中​​

​​        ①导包​​

​​        ②对象实例化​​

​​2、通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取​​

​​        ①tagName​​

​​        ②find​​

​​        ③select​​

​​        ④获取文本标签之间的文本数据​​

​​        ⑤获取标签的属性值​​

​​ 二、需求说明​​

​​三、步骤​​

​​四、源码​​

一、bs4数据解析原理

1、环境安装

—  pip install bs4

    —  pip install lxml      

2、实例化一个BeautifulSoup对象,并且将页面源码数据加载到该对象中

        ①导包

from bs4 import BeautifulSoup      

        ②对象实例化

(1)本地

fp = open('./jingdong.html','r',encoding='utf-8')#本地文件
soup = BeautifulSoup(fp,'lxml')      

(2)互联网

page_text = response.text

soup = BeatifulSoup(page_text,'lxml')      

2、通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取

        ①tagName

soup.tagName:返回的是文档中第一次出现的tagName对应的标签

        ②find

— soup.find():

        — soup('tagName'):等同于soup.div

        — 属性定位:

                — soup.find('div',class_/id/attr='song')

        — soup.find_all('tagName'):返回的是符合要求的所有标签(列表)

        ③select

— select('某种选择器(id,class,标签.....选择器)'),返回的是一个列表。

— 层级选择器:

        — soup.select('.tang > ul > li > a')[0]:>表示的是一个层级

        —soup.select('.tang > ul li > a')[0]:空格表示的是多个层级

        ④获取文本标签之间的文本数据

— soup.a.text/string/get_text()(两个属性,一个方法)

— text/get_text():可以获取某一个标签中所有的文本内容(即使不是直系标签)

— string:只可以获取该标签下面直系的文本内容

        ⑤获取标签的属性值

 二、需求说明

三、步骤

四、源码

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
#需求:爬取三国演义小说所有的章节标题和章节内容http://www.shicimingju.com/book/sangguoyanyi.html
if __name__ == '__main__':
    #对首页的页面数据进行爬取
    url = 'https://book.qidian.com/info/1023589911'
    headers = {
        'User-Agent': 'Mozilla  /5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
    }
    page_text = requests.get(url=url,headers=headers).text

    #在首页中解析出章节的标题和详情页的url
    #1.实例化BeautifulSoup对象,需要将页面源码数据加载到该对象中
    soup = BeautifulSoup(page_text,'lxml')
    #解析章节标题和详情页url
    a_list = soup.select('.detail > p > a')
    fp = open('./sanguo.txt','w',encoding='utf-8')
    for x in a_list:
        title = x.string
        detail_url = 'https:'+ x['href']
        #对详情页发起请求,解析出章节内容
        detail_page_text = requests.get(url=detail_url,headers=headers).text
        #解析出详情页中相关的章节内容
        detail_soup = BeautifulSoup(detail_page_text,'lxml')
        tag = detail_soup.find('div',class_='read-content j_readContent')
        # print(detail_soup)
        # tag = detail_soup.select('.read-content j_readContent ')#
        # tag = detail_soup.select('.content-wrap')
        content = tag.text
        fp.write(title+':'+content+'\n')
        print(title,'爬取成功')