数据解析_bs进行数据解析

1、bs4进行数据解析

  数据解析的原理

     1、标签定位

     2、提取标签,标签属性中存储的数据值

       bs4数据解析的原理

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

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

  2、环境安装

  -- pip install  bs4

      -- pip install  lxml

3、基本知识

  1、实例化BeautifulSoup对象:

    from bs4 import BeautifulSoup

    实例化:1、将本地的html文档中的数据加载到该对象中         

 fp = open('./test.html','r',encoding='utf-8')
    #将本地的html文档中的数据加载到改对象中
    soup = BeautifulSoup(fp,"lxml")
    print(soup)

        2、将互联网上获取的页面源码加载到改对象中(常用)

page_text = response.text
soup = BeautifulSoup(page_text,'lxml')

     2、Beautiful提供的属性和方法

        1、soup.tagName   例如:soup.a   就是获取第一个a标签

   2、find()

                 soup.find('tagName')    如 soup.find('div')      返回的也是第一个div,和前面是等价的

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

                 soup.find_all()   返回多个数据  find_all('tagName') 返回的是一个列表

      3、select()  最好用

           select('某种选择器')  可以是id、类、标签选择器  返回一个列表  soup.select('.tang') 

      soup.select('.tang >ul >li > a')[0]

      soup.select('.tang >ul >li  a')[0]

    4、获取标签之间的文本数据    soup.a.text   soup.a.string    soup.a.get_text()

    区别:text/get_text()   可以获取标签之间的所有文本内容,可以是后代

          string只可以获取标签的子元素内容

    5、获取标签的属性值

        soup.a['href']

 4、实战

from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
    #爬取三国演义小说的所有章节和内容
    url = "http://www.shicimingju.com/book/sanguoyanyi.html"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
    }
    # 1、对首页的数据进行爬取
    page_text = requests.get(url = url,headers=headers).text
    # 2、在首页中解析出章节的标题和详情页的url
    #1、实例化beautifulSoup对象

    soup = BeautifulSoup(page_text,'lxml')
    #2、解析章节标题
    li_list = soup.select('.book-mulu > ul > li')
    #打开一个文本文件就可以了
    fp = open('./sanguo.txt','w',encoding='utf-8')
    for li in li_list:
        title = li.a.string
        detail_url = "http://www.shicimingju.com"+li.a['href']
        # 对详情页发起请求,解析出章节内容
        detail_page_text = requests.get(url = detail_url,headers=headers).text
        #解析出详情页中对应的章节内容
        detail_soup = BeautifulSoup(detail_page_text,'lxml')
        div_tag = detail_soup.find('div',class_ = 'chapter_content')
        #解析到了章节的内容
        content = div_tag.text
        fp.write(title+":"+content+"
")
        print(title,'爬取成功')

 

原文地址:https://www.cnblogs.com/sunflying/p/13193091.html