前言
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】
修改瀏覽器的部分屬性, 繞過檢測
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)) # 盡量避免人機檢測 隨機延遲