8.1 淘寶實戰selinum代碼完整

案例三:爬取淘寶)
1 mongodb打開方法之前講過。+++
2  如果用requests的方式需要準備一定量的ip,所以此次採用selinum方式
3  注意此次使用pyquery解析,和前端掛鉤。
--------------------------------------------------------------------------------


實戰環節
爬取淘寶網有關“鞋子”的商品信息,並把爬取的數據存儲在MongoDB數據庫中(這裏爲了方便大家測試,只是把信息輸出)
首先前往淘寶網;
分析搜索框的xpath語句,並send_keys(‘鞋子’);
分析頁面,找到每條商品的信息,使用xpath提取數據並將其存儲成字典的格式,輸出該字典;
找到下一頁的按鈕,模擬點擊它,並循環第3步,直到循環結束 。

文章參考鏈接必看[:](https://www.cnblogs.com/zhaof/p/6953241.html)[https://www.cnblogs.com/zhaof/p/6953241.html]

css基礎 :#表示id ,.表示class

而淘寶頁面上那個value是淘寶工程師做的一個下一頁的預處理,而我們要獲取的不是value,而是input,所以可以不用管

class=“A B”這代表有A和B兩個類

完整代碼:
#! /usr/bin/env python
# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.by import By  #查找元素的方法,此次用於搜索框查找
from selenium.webdriver.support.ui import WebDriverWait #顯示等待,設置最長等待時間,此次用於打開鏈接的最長等待時間

from selenium.webdriver.support import expected_conditions as EC #EC.presence_of_element_located()是確認元素是否已經出現了或者可點擊等
from selenium.common.exceptions import TimeoutException #異常處理,try exceptions
from pyquery import PyQuery as pq  #基於前端的解析代碼的工具
import re  #正則表達式
from pymongo import MongoClient
from selenium.webdriver.common.keys import Keys

client = MongoClient()
db = client.taobao
yurongfu = db.yurongfu #創建羽絨服集合

driver = webdriver.Chrome() #打開Chrome瀏覽器,C要大寫
wait = WebDriverWait(driver,10) #設置瀏覽器等待時間

#進入淘寶網,輸入鞋子,返回頁面
def search():
    try:
        driver.get('https://www.taobao.com/')
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))) #定位輸入框
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_TSearchForm > div.search-button > button'))) #定位搜索按鈕
        input.send_keys(u'羽絨服') #輸入羽絨服
        submit.click() #模擬提交按鈕
        total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.total'))) #確保所有頁數信息加載完畢
        get_products() #調用得到所有產品函數
        return total.text
    except TimeoutException:
        return search()

#跳轉到下一頁
def next_page(page_number):
    try:
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input"))) #相當於input這個頁碼輸入框輸入了page_number
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit'))) #定位確定按鈕
        input.clear() #clear() 函數用於刪除字典內所有元素
        input.send_keys(page_number)
        submit.click()
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number))) #某個元素文本包含某文字
        get_products()
    except TimeoutException:
        next_page(page_number)

#得到淘寶商品信息
def get_products():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))
    html = driver.page_source
    doc = pq(html)
    #pyquery (driver.page_source)就相當於requests.get獲取的內容
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product = {
            'image':item.find('.pic .img').attr('src'),#用這個類代表這個標籤
            'price':item.find('.price').text(),
            'deal':item.find('.deal-cnt').text()[:-3],
            'title':item.find('.title').text(),
            'shop':item.find('.shop').text(),
            'location':item.find('.location').text()
        }
        print(product)
        yurongfu.insert(product)

def main():  #定義主函數
    total = search()
    total= int(re.compile('(\d+)').search(total).group(1))
        #爬取所有的數據時,把10替換爲total+1
    for i in range(1,10):
        next_page(i)

if __name__ == '__main__':
    main()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章