天天看点

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爬虫爬取京东商品信息并数据可视化