天天看點

seleinum爬蟲爬取京東商品資訊并資料可視化

seleinum簡介

Selenium是一個Web的自動化測試工具,最初是為網站自動化測試而開發的,類型像我們玩遊戲用的按鍵精靈,可以按指定的指令自動操作,不同是Selenium 可以直接運作在浏覽器上,它支援所有主流的浏覽器(包括PhantomJS這些無界面的浏覽器)

官方文檔

http://selenium-python.readthedocs.io/index.html

為什麼要用seleinum

使用 Selenium 的最大好處是:Selenium測試直接在浏覽器中運作,就像真實使用者所做的一樣。Selenium測試可以在 Windows、Linux 和 Macintosh上的 Internet Explorer、Chrome和 Firefox 中運作,其他測試工具都不能覆寫如此多的平台。

seleinum爬蟲爬取京東商品資訊并資料可視化

搜尋功能

通過

driver.get(‘http://www.jd.com’)

通路京東官網的網址,然後通過xpath定位方式找到搜尋框和搜尋按鈕,通過seleinum預設的方法執行按鍵操作。

def search():
    try:
        driver.get("http://www.jd.com")
        input = wait.until(EC.presence_of_element_located((By.XPATH,'.//*[@id="key"]')))#等待條件完成後再執行操作
        button = wait.until(EC.element_to_be_clickable((By.XPATH,'.//*[@id="search"]/div/div[2]/button')))
        input.send_keys(keyword)
        button.click()
        total = wait.until(EC.presence_of_element_located((By.XPATH,'.//*[@id="J_bottomPage"]/span[2]/em[1]/b'))).text#擷取總頁數
        print(total)
    except TimeoutError:
        search()
           

擷取商品資訊功能

我通過pyquery的方法去定位我想要的資訊,并把爬取到的資訊存到txt檔案當中去。并通過repalce()方法替換掉多餘的資訊實作爬取内容格式的一緻性。

def get_products():
    try:
        html = driver.page_source
        doc = pq(html)
        items = doc('#J_goodsList .gl-i-wrap').items()  # 先id,後class
        ####字典形式存儲####
        for item in items:
            name = item.find('em').text().replace("\n",'').replace("¥",'')
            # price = item.find('.p-price').text()
            # shop = item.find('.p-shop').text()
            print(name)
            try:
                with open("DATA.txt", 'a', encoding="utf-8") as f:
                    f.write(name + '\n')
            finally:
                f.close()
    except TimeoutError:
        get_products()
           

pyquery學習教程

https://www.cnblogs.com/themost/p/6903742.html
           

翻頁功能

當我們爬取完一頁之後,需要翻頁繼續爬取,就需要有一個翻頁器,通過xpath定位到下方的輸入頁碼的框框,輸入數字,點選确定。需要注意的是,這中間有一個滑倒頁面中部的操作,作用是讓剩餘的網頁加載出來,因為一頁京東商品并不是一次性顯示出來的,然後sleep1秒給出緩沖時間。

def next_page():
    num = 0
    while num !=3:
        print("第%s頁" %str(num+1))
        num += 1
        wait.until(EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/input"))).clear()
        wait.until(EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/input"))).send_keys(num+1)
        wait.until((EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/a")))).click()
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/input").clear()
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/input").send_keys(num)
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/a").click()
        driver.execute_script("window.scrollBy(0, 5000)")#滑動到頁面中部,把動态加載的内容加載出來
        time.sleep(1)
        get_products()
           

詞雲功能

我要實作的資料可視化是采用詞雲展示的方法去顯示相關搜尋内容中出現頻率最高的詞語,如果賣家使用這個爬蟲的話,就會知道什麼産品出現的頻率最高,然後根據詞雲展示的結果進貨。

def word_cloud():
    f = open('DATA.txt', 'r', encoding='utf-8').read()
    w = wordcloud.WordCloud(width=1000, height=700, background_color='white', font_path='msyh.ttc')
    w.generate(f)
    w.to_file('output.png')
    plt.imshow(w)
    plt.axis("off")
    plt.show()
           

wordcloud教程

https://blog.csdn.net/FontThrone/article/details/72775865

完整代碼

# coding=utf-8
import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from pyquery import PyQuery as pq
import wordcloud
import matplotlib.pyplot as plt

driver = webdriver.Firefox()
wait = WebDriverWait(driver,10)
keyword = 'python爬蟲'

def search():
    try:
        driver.get("http://www.jd.com")
        input = wait.until(EC.presence_of_element_located((By.XPATH,'.//*[@id="key"]')))#等待條件完成後再執行操作
        button = wait.until(EC.element_to_be_clickable((By.XPATH,'.//*[@id="search"]/div/div[2]/button')))
        input.send_keys(keyword)
        button.click()
        total = wait.until(EC.presence_of_element_located((By.XPATH,'.//*[@id="J_bottomPage"]/span[2]/em[1]/b'))).text
        print(total)
    except TimeoutError:
        search()

def get_products():
    try:
        html = driver.page_source
        doc = pq(html)
        items = doc('#J_goodsList .gl-i-wrap').items()  # 先id,後class
        ####字典形式存儲####
        for item in items:
            name = item.find('em').text().replace("\n",'').replace("¥",'')
            # price = item.find('.p-price').text()
            # shop = item.find('.p-shop').text()
            print(name)
            try:
                with open("DATA.txt", 'a', encoding="utf-8") as f:
                    f.write(name + '\n')
            finally:
                f.close()
    except TimeoutError:
        get_products()

def next_page():
    num = 0
    while num !=3:#友善起見,僅爬取了前三頁
        print("第%s頁" %str(num+1))
        num += 1
        wait.until(EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/input"))).clear()
        wait.until(EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/input"))).send_keys(num+1)
        wait.until((EC.presence_of_element_located((By.XPATH,".//*[@id='J_bottomPage']/span[2]/a")))).click()
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/input").clear()
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/input").send_keys(num)
        # driver.find_element_by_xpath(".//*[@id='J_bottomPage']/span[2]/a").click()
        driver.execute_script("window.scrollBy(0, 5000)")#滑動到頁面中部,把動态加載的内容加載出來
        time.sleep(1)
        get_products()

def word_cloud():
    f = open('DATA.txt', 'r', encoding='utf-8').read()
    w = wordcloud.WordCloud(width=1000, height=700, background_color='white', font_path='msyh.ttc')
    w.generate(f)
    w.to_file('output.png')
    plt.imshow(w)
    plt.axis("off")
    plt.show()

if __name__ == '__main__':
    search()
    next_page()
    word_cloud()
    driver.quit()
           

運作結果展示:

seleinum爬蟲爬取京東商品資訊并資料可視化