1. 程式人生 > 其它 >雙十一手剁完了嗎?教你用Python再剁一遍(Python模擬登入,採集淘寶商品資料)

雙十一手剁完了嗎?教你用Python再剁一遍(Python模擬登入,採集淘寶商品資料)

前言

11月4日,中國消費者協會在官網釋出消費提示,提醒消費者“雙十一”購物六點注意事項。主要內容就是對於雙十一的“低價”不可迷信,提防商家套路。那麼對於我們要怎麼樣才能選擇真正的底價好貨呢?

今天帶大家使用python+selenium工具獲取這些公開的商家資料,可以採集商品的價格和評價做對比

環境介紹

  • python 3.8
  • pycharm
  • selenium
  • csv
  • time
  • random

安裝所需的第三方模組

from selenium import webdriver
import time  # 時間模組, 可以用於程式的延遲
import random  #
隨機數模組 from constants import TAO_USERNAME1, TAO_PASSWORD1 import csv # 資料儲存的模組

建立一個瀏覽器

driver = webdriver.Chrome()

執行自動化瀏覽器的操作

driver.get('https://www.taobao.com/')
driver.implicitly_wait(10)  # 設定瀏覽器的等待,載入資料
driver.maximize_window()  # 最大化瀏覽器

搜尋功能

首先,開啟開發者工具;然後選擇用左上角的工具選中搜索框,然後會幫我們定位到當前選中元素的標籤;最後,右鍵,選擇Copy,再選擇Xpath語法

def search_product(keyword):
    driver.find_element_by_xpath('//*[@id="q"]').send_keys(keyword)
    time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲

    driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()
    time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲

word = input('
請輸入你要搜尋商品的關鍵字:') # 呼叫商品搜尋的函式 search_product(word)

登入介面

用上面相同的方法,找到所需元素

driver.find_element_by_xpath('//*[@id="f-login-id"]').send_keys(TAO_USERNAME1)
time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲

driver.find_element_by_xpath('//*[@id="f-login-password"]').send_keys(TAO_PASSWORD1)
time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲

driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()
time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲


對於本篇文章有疑問的同學可以加【資料白嫖、解答交流群:1136201545】

selenium操作的瀏覽器被識別了, 無法登入

修改瀏覽器的部分屬性, 繞過檢測

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",
            {"source": """Object.defineProperty(navigator, 'webdriver', {get: () => false})"""})

解析商品資料

def parse_data():
    divs = driver.find_elements_by_xpath('//div[@class="grid g-clearfx"]/div/div')  #  所有的div標籤

    for div in divs:
        try:
            info = div.find_element_by_xpath('.//div[@class="row row-2 title"]/a').text
            price = div.find_element_by_xpath('.//strong').text + ''
            deal = div.find_element_by_xpath('.//div[@class="deal-cnt"]').text
            name = div.find_element_by_xpath('.//div[@class="shop"]/a/span[2]').text
            location = div.find_element_by_xpath('.//div[@class="location"]').text
            detail_url = div.find_element_by_xpath('.//div[@class="pic"]/a').get_attribute('href')

            print(info, price, deal, name, location, detail_url)

儲存

with open('某寶.csv', mode='a', encoding='utf-8', newline='') as f:
    csv_write = csv.writer(f)
    csv_write.writerow([info, price, deal, name, location, detail_url])

翻頁爬取

找到頁面的規律,為一個等差數列,而第一頁為0

for page in range(100): # 012
    print(f'\n==================正在抓取第{page + 1}頁資料====================')
    url = f'https://s.taobao.com/search?q=%E5%B7%B4%E9%BB%8E%E4%B8%96%E5%AE%B6&s={page * 44}'
    # 解析商品資料
    parse_data()
    time.sleep(random.randint(1, 3))  # 儘量避免人機檢測  隨機延遲

最後執行程式碼,得到結果