天天看點

Selenium分頁爬取淘寶商品資訊這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

1.分析連結

打開淘寶網,我們在搜尋框搜尋ipad,産生連結為 https://s.taobao.com/search?q=ipad

需要擷取的資訊有商品圖檔,價格,标題,位址等資訊,如下圖所示。

Selenium分頁爬取淘寶商品資訊這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

在這裡,我們爬取的頁數按照跳轉頁數計算防止部分界面資料不穩定造成後續爬取失敗。

Selenium分頁爬取淘寶商品資訊這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

2.代碼實作

首先,我們擷取商品清單,代碼如下:

from selenium import webdriver
from selenium.common.exceptions import  TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()
wait = WebDriverWait(browser,12)
KEYWORD = 'ipad'

def index_page(page):  #獲得商品清單
    print('正在爬取第',page,'頁')
    try:
        url = 'https://s.taobao.com/search?q='+ quote(KEYWORD)
        browser.get(url)
        if page > 1:
            input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#q')))
            submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager div.form > span.btn.J_Submit')))
            input.clear()
            input.send_keys(page)
            submit.click()
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager li.item.active > span'),str(page)))
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.m-itemlist .items .item')))
        get_products()
    except TimeoutException:
        index_page(page)
           

【代碼解讀】首先定義搜尋框imput和确定按鈕submit,通過分頁那張圖檔我們可以定位到這兩個位置,可通過開發者選項,在浏覽器“搜尋框”處右鍵“檢查”,檢視element頁籤,查找元素位置,後面的元素定位均用此方法。然後搜尋框清空,再輸入page,模拟點選按鈕進行搜尋。

點選之後,判斷目前頁面是否大于1,即text_to_be_present_in_elements,判斷方法為頁碼高亮處的數字與輸入的跳轉頁面比較。之後等待商品資訊加載出來,即presence_of_element_located。最後利用get_products()方法解析商品資料。

from pyquery import PyQuery as pq

def get_products():   #提取商品資料
    html = browser.page_source
    doc = pq(html)
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product = {
            'image':item.find('.pic .img').attr('data-src'),   #商品圖檔
            'price':item.find('.price').text(),          #價格
            'deal':item.find('.deal-cnt').text(),              #付款人數
            'title':item.find('.title').text(),          #商品标題
            'shop':item.find('.shop').text(),         #店鋪名稱
            'location':item.find('.location').text()            #位址
        }
        print(product)
        #save_to_mongo(product)
           

最後,周遊每頁,調用main()方法即可,代碼如下:

def main():
    for i in range(1,3):
         index_page(i)
    browser.close()

if __name__ == '__main__':
    main()
           

pycharm資料運作如下:

Selenium分頁爬取淘寶商品資訊這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

MongoDB運作截圖如下:

Selenium分頁爬取淘寶商品資訊這一節利用selenium爬取淘寶商品資訊并儲存至mongodb資料庫

注:MongoDB資料庫相關代碼在本文中已被注釋

本節代碼已上傳至github:https://github.com/lizeyang18/Pythpn3WebSpiser-taobao

學習永無止境,感謝閱讀~