數據解析之BeautifulSoup解析


一,安裝

pip install bs4

或者:

- 需要將pip源設置為國內源,阿里源、豆瓣源、網易源等
   - windows
    (1)打開文件資源管理器(文件夾地址欄中)
    (2)地址欄上面輸入 %appdata%3)在這里面新建一個文件夾  pip
    (4)在pip文件夾里面新建一個文件叫做  pip.ini ,內容寫如下即可
        [global]
        timeout = 6000
        index-url = https://mirrors.aliyun.com/pypi/simple/
        trusted-host = mirrors.aliyun.com
   - linux
    (1)cd ~2)mkdir ~/.pip
    (3)vi ~/.pip/pip.conf
    (4)編輯內容,和windows一模一樣
- 需要安裝:pip install bs4
     bs4在使用時候需要一個第三方庫,把這個庫也安裝一下
     pip install lxml

二,基本使用

使用流程:       
    - 導包:from bs4 import BeautifulSoup
    - 使用方式:可以將一個html文檔,轉化為BeautifulSoup對象,然后通過對象的方法或者屬性去查找指定的節點內容
        (1)轉化本地文件:
             - soup = BeautifulSoup(open('本地文件'), 'lxml')
        (2)轉化網絡文件:
             - soup = BeautifulSoup('字符串類型或者字節類型', 'lxml')
        (3)打印soup對象顯示內容為html文件中的內容

基礎鞏固:
    (1)根據標簽名查找
        - soup.a   只能找到第一個符合要求的標簽
    (2)獲取屬性
        - soup.a.attrs  獲取a所有的屬性和屬性值,返回一個字典
        - soup.a.attrs['href']   獲取href屬性
        - soup.a['href']   也可簡寫為這種形式
    (3)獲取內容
        - soup.a.string  # 獲取直系標簽的文本
        - soup.a.text  # 獲取所有
        - soup.a.get_text()  # 獲取所有
       【注意】如果標簽還有標簽,那么string獲取到的結果為None,而其它兩個,可以獲取文本內容
    (4)find:找到第一個符合要求的標簽
        - soup.find('a')  找到第一個符合要求的
        - soup.find('a', title="xxx")
        - soup.find('a', alt="xxx")
        - soup.find('a', class_="xxx")
        - soup.find('a', id="xxx")
    (5)find_all:找到所有符合要求的標簽
        - soup.find_all('a')
        - soup.find_all(['a','b']) 找到所有的a和b標簽
        - soup.find_all('a', limit=2)  限制前兩個
    (6)根據選擇器選擇指定的內容
               select:soup.select('#feng')
        - 常見的選擇器:標簽選擇器(a)、類選擇器(.)、id選擇器(#)、層級選擇器
            - 層級選擇器:
                div .dudu #lala .meme .xixi  下面好多級
                div > p > a > .lala          只能是下面一級
        【注意】select選擇器返回永遠是列表,需要通過下標提取指定的對象

ex:使用bs4實現將詩詞名句網站中三國演義小說的每一章的內容爬去到本地磁盤進行存儲   http://www.shicimingju.com/book/sanguoyanyi.html 

import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36"
}

def get_content(url):
    """
    獲取url中的頁面內容
    """
    page_text = requests.get(url=url, headers=headers).text
    soup = BeautifulSoup(page_text, "lxml")
    return soup.find("div", class_="chapter_content").get_text()

url = "http://www.shicimingju.com/book/sanguoyanyi.html"
response = requests.get(url=url, headers=headers)
page_text = response.text
soup = BeautifulSoup(page_text, "lxml")
li_list = soup.select(".book-mulu > ul > li")  # 獲取的所有的li標簽列表
fp = open("sanguo.txt", "w", encoding="utf-8")
for li in li_list:
    title = li.a.string  # 獲取li標簽下的a標簽的內容
    content_url = "http://www.shicimingju.com" + li.a["href"]
    content = get_content(content_url)
    fp.write(title + "\n" + content)
    print(title + "已經下載成功")
fp.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM