天天看點

資料解析之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,'爬取成功')