[ python] 爬虫笔记(四) 数据解析之bs4解析

聚焦爬虫

爬取页面中指定的内容
编码流程:
指定url——发起请求——获取响应数据——数据解析——进行持久化存储

数据解析分类

  • 正则匹配
  • bs4
  • xpath

数据解析原理
在这里插入图片描述

bs4数据解析的原理:

  • 实例化一个BeautifulSoup对象,并且将页面源码数据加载到该对象中
  • 通过调用BS对象中相关属性方法进行标签定位和数据提取

首先

  • pip install bs4
  • pip install lxml

如何实例化Beautiful对象
soup = BeautifulSoup(file,'lxml)

  • from bs4 import BeautifulSoup

  • 对象实例化:

    • 将本地html文档中的数据加载到该对象
    • 将互联网上获取的页面源码加载到该对象
  • 提供用于解析的属性和方法:

    • soup.tagName 返回的是html中第一次出现的tagName标签
    • soup.find(‘tagName’)
      • == soup.tagName,等同于上面一条
      • 定位,如soup.find(‘div’,class_/id/attr=‘song’) #class要加下划线
    • soup.find_all(‘tagName’) 返回要求的所有标签
    • soup.select(’.tang’) 选择器
      • select('某种选择器(id,class,标签)‘),返回的是一个列表
      • soup.select(’.tang > ul > li > a’)[0] >表示的是一个层级,空格表示多个层级soup.select(’.tang > ul a’)[0]
    • 获取标签之间文本数据
      • soup.a.text/string/get_text()
      • text/get_text()可以获取某一个标签所有文本内容,string只可以获取该标签下面直系的文本内容
    • 获取标签属性值
      • soup.select(’.tang > ul > li > a’)[0][‘href’]
from bs4 import BeautifulSoup
import requests
import re
import os
#爬取三国演义小说所有的章节和章节内容
if __name__ == "__main__":

    if not os.path.exists('三国演义'):
        os.mkdir('三国演义')

    ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4209.400"
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
    headers = {
    
    
        "User-Agent":ua,
    }
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text,'lxml')
    mulu = soup.select('.book-mulu > ul >li > a')
    urc = soup.select('.book-mulu > ul > li > a')

    ex = '<a href="(.*?)">.*?'

    for i in range(len(urc)):

        file_name = './三国演义/' + mulu[i].text + ".txt"
        f = open(file_name,'w',encoding='utf-8')
        a = re.findall(ex, str(urc[i]))
        content_url = 'https://www.shicimingju.com' + a[0] #该章内容链接

        content_all = requests.get(url=content_url,headers=headers)
        content_soup = BeautifulSoup(content_all.text,'lxml')
        for content_p in content_soup.select('.chapter_content p'):
            f.write("\n  ")
            f.write(content_p.text)

        f.close()

在这里插入图片描述
在这里插入图片描述
舒服了

猜你喜欢

转载自blog.csdn.net/Sgmple/article/details/112059432