python帶你采集當當網(wǎng)商品及評論數(shù)據(jù)并實現(xiàn)詞云圖

前言 ??

嗨嘍,大家好呀~這里是愛看美女的茜茜吶

本次采集網(wǎng)介紹:圖書頻道-全球最大中文網(wǎng)上書店

專業(yè)提供小說傳記,青春文學,成功勵志,投資理財?shù)雀髌奉悎D書

暢銷榜最新報價、促銷、評論信息,引領最新網(wǎng)上購書體驗!

環(huán)境使用 ??:

  • Python 3.8

  • Pycharm

模塊使用 ??:

  • requests >>> pip install requests

  • parsel >>> pip install parsel

  • csv

爬蟲基本思路流程 ??:

一. 數(shù)據(jù)來源分析

  1. 確定自己采集數(shù)據(jù)內(nèi)容
  2. 抓包分析,自己想要數(shù)據(jù)來自哪里 ---> 請求那個url地址得到想要的數(shù)據(jù)
  • 開發(fā)者工具抓包分析 F12 或者 鼠標右鍵點擊檢查 選擇 network(網(wǎng)絡), 刷新網(wǎng)頁
  • 通過關鍵字(我們想要數(shù)據(jù)比如: 書名) 去搜索數(shù)據(jù)包是那個 ---> 確定請求是那個網(wǎng)址得到數(shù)據(jù)內(nèi)容

請求這個網(wǎng)站 就可以得到我們想要數(shù)據(jù)內(nèi)容

二. 代碼實現(xiàn)步驟:

  1. 發(fā)送請求, 模擬瀏覽器對于url發(fā)送請求

  2. 獲取數(shù)據(jù), 獲取服務器返回響應數(shù)據(jù) ---> 開發(fā)者工具里面response

  3. 解析數(shù)據(jù), 提取我們想要數(shù)據(jù)內(nèi)容, 書籍基本信息

  4. 保存數(shù)據(jù), 保存表格里面

數(shù)據(jù)采集 ??

# 導入數(shù)據(jù)請求模塊  ---> 第三方模塊 需要 在cmd 里面 pip install requests
import requests
# 導入數(shù)據(jù)解析模塊 ---> 第三方模塊 需要 在cmd 里面 pip install parsel
import parsel
# 導入csv模塊 ---> 內(nèi)置模塊 不需要安裝
import csv

# 創(chuàng)建文件
f = open('書籍data25頁.csv', mode='a', encoding='utf-8', newline='')
# f文件對象 fieldnames 字段名 ---> 表格第一行 作為表頭
csv_writer = csv.DictWriter(f, fieldnames=[
    '標題',
    '評論',
    '推薦',
    '作者',
    '日期',
    '出版社',
    '售價',
    '原價',
    '折扣',
    '電子書',
    '詳情頁',
])
# 源碼、解答、教程加Q裙:261823976
# 寫入表頭
csv_writer.writeheader()
"""
1. 發(fā)送請求, 模擬瀏覽器對于url發(fā)送請求
    - 等號左邊是定義變量名
    - 模擬瀏覽器 ---> 請求頭
        headers ---> 在開發(fā)者工具里面復制粘貼 字典數(shù)據(jù)類型
        一種簡單反反爬手段, 防止被服務器識別出來是爬蟲程序
    - 使用什么請求方式, 根據(jù)開發(fā)者工具來的
"""
for page in range(1, 26): #  1,26 是取1-25的數(shù)字, 不包含26
    # 確定請求網(wǎng)址
    url = f'http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-recent7-0-0-1-{page}'
    # 模擬瀏覽器 ---> 請求頭
    headers = {
        # User-Agent 用戶代理 表示瀏覽器基本身份標識
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
    }
    # 發(fā)送請求 返回的響應對象 ---> <Response [200]>: <> 表示對象  response 響應回復  200狀態(tài)碼 表示請求成功
    response = requests.get(url=url, headers=headers)
    print(response)
    # 2. 獲取數(shù)據(jù), 獲取服務器返回響應數(shù)據(jù) ---> 開發(fā)者工具里面 response  print(response.text)
    """
    3. 解析數(shù)據(jù), 提取我們想要數(shù)據(jù)內(nèi)容, 書籍基本信息
    根據(jù)得到數(shù)據(jù)類型以及我們想要數(shù)據(jù)內(nèi)容, 選擇最適合解析方法:
        - re正則表達式
        - css選擇器
        - xpath
    xpath --->  根據(jù)標簽節(jié)點提取數(shù)據(jù)
    css選擇器 ---> 根據(jù)標簽屬性提取數(shù)據(jù)內(nèi)容
        css語法匹配  不會 1  會的 2
        復制粘貼會不會 ---> ctrl + C  ctrl + v
    """
    # 轉數(shù)據(jù)類型 <Selector xpath=None data='<html xmlns="http://www.w3.org/1999/x...'>
    selector = parsel.Selector(response.text)
    # 第一次提取 提取所有l(wèi)i標簽 --> 返回列表, 元素Selector對象
    lis = selector.css('.bang_list_mode li')
    # for循環(huán)遍歷 之后進行二次提取 我們想要內(nèi)容
    for li in lis:
        """
        attr() 屬性選擇器 
        a::attr(title) ---> 獲取a標簽里面title屬性
        get() 獲取一個 第一個 
        """
        title = li.css('.name a::attr(title)').get()  # 標題
        star = li.css('.star a::text').get().replace('條評論', '')  # 評論
        recommend = li.css('.tuijian::text').get().replace('推薦', '')  # 推薦
        author = li.css('.publisher_info a::attr(title)').get()  # 作者
        date = li.css('.publisher_info span::text').get()  # 日期
        press = li.css('div:nth-child(6) a::text').get()  # 出版社
        price_n = li.css('.price .price_n::text').get()  # 售價
        price_r = li.css('.price .price_r::text').get()  # 原價
        price_s = li.css('.price .price_s::text').get().replace('折', '')  # 折扣
        price_e = li.css('.price .price_e .price_n::text').get()  # 電子書
        href = li.css('.name a::attr(href)').get()  # 詳情頁
        # 保存數(shù)據(jù)
        源碼、解答、教程加Q裙:261823976
        dit = {
            '標題': title,
            '評論': star,
            '推薦': recommend,
            '作者': author,
            '日期': date,
            '出版社': press,
            '售價': price_n,
            '原價': price_r,
            '折扣': price_s,
            '電子書': price_e,
            '詳情頁': href,
        }
        # 寫入數(shù)據(jù)
        csv_writer.writerow(dit)
        print(title, star, recommend, author, date, press, price_n, price_r, price_s, price_e, href, sep=' | ')

評論 ??

# 導入數(shù)據(jù)請求模塊
import time
import requests
import re
for page in range(1, 11):
    time.sleep(1.5)
    # 確定網(wǎng)址
    源碼、解答、教程加Q裙:261823976
    url = 'http://product.dangdang.com/index.php'
    # 請求參數(shù)
    data = {
        'r': 'comment/list',
        'productId': '27898031',
        'categoryPath': '01.43.77.07.00.00',
        'mainProductId': '27898031',
        'mediumId': '0',
        'pageIndex': page,
        'sortType': '1',
        'filterType': '1',
        'isSystem': '1',
        'tagId': '0',
        'tagFilterCount': '0',
        'template': 'publish',
        'long_or_short': 'short',
    }
    headers = {
        'Cookie': '__permanent_id=20220526142043051185927786403737954; dest_area=country_id%3D9000%26province_id%3D111%26city_id%20%3D0%26district_id%3D0%26town_id%3D0; ddscreen=2; secret_key=f4022441400c500aa79d59edd8918a6e; __visit_id=20220723213635653213297242210260506; __out_refer=; pos_6_start=1658583812022; pos_6_end=1658583812593; __trace_id=20220723214559176959858324136999851; __rpm=p_27898031.comment_body..1658583937494%7Cp_27898031.comment_body..1658583997600',
        'Host': 'product.dangdang.com',
        'Referer': 'http://product.dangdang.com/27898031.html',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
    }
    response = requests.get(url=url, params=data, headers=headers)
    html_data = response.json()['data']['list']['html']
    content_list = re.findall("<span><a href='.*?' target='_blank'>(.*?)</a></span>", html_data)
    for content in content_list:
        with open('評論.txt', mode='a', encoding='utf-8') as f:
            f.write(content)
            f.write('\n')
        print(content)

詞云圖 ??

import jieba
import wordcloud
import imageio
# 讀取圖片
py = imageio.imread('python.png')
# 打開文件
f = open('評論.txt', encoding='utf-8')
# 讀取內(nèi)容
txt = f.read()
# jieba模塊進行分詞  ---> 列表
txt_list = jieba.lcut(txt)
print(txt_list)
# join把列表合成字符串
string = ' '.join(txt_list)
# 使用詞云庫
wc = wordcloud.WordCloud(
    height=300,  # 高度
    width=500,  # 寬度
    background_color='white',  # 背景顏色
    font_path='msyh.ttc',  # 字體
    scale=15, # 輪廓
    stopwords={'的', '了', '很', '也'},  # 停用詞
    mask=py  # 自定義詞云圖樣式
)
wc.generate(string)  # 需要做詞云數(shù)據(jù)傳入進去
wc.to_file('1.png')  # 輸入圖片

尾語 ??

感謝你觀看我的文章吶~本次航班到這里就結束啦 ??

希望本篇文章有對你帶來幫助 ??,有學習到一點知識~

躲起來的星星??也在努力發(fā)光,你也要努力加油(讓我們一起努力叭)。

最后,博主要一下你們的三連呀(點贊、評論、收藏),不要錢的還是可以搞一搞的嘛~

不知道評論啥的,即使扣個6666也是對博主的鼓舞吖 ?? 感謝 ??

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容