練習

  • 觀察 http://24h.pchome.com.tw/region/DHBE 並撰寫爬蟲程式
  • 判斷是否為 JavaScript rendered website
  • 設定 Implicit Wait
  • 透過 XPath 定位
  • 抓取商品的名稱與價格

In [1]:
import os

from selenium import webdriver
from selenium.webdriver.common.by import By

url = 'http://24h.pchome.com.tw/region/DHBE'

In [2]:
try:
    driver = webdriver.Chrome()
    driver.get(url)
    driver.maximize_window()
    driver.implicitly_wait(10)
    
    # get web elements
    items = driver.find_elements(By.XPATH, '//dl[@id="Block12Container50"]/dd')
    
    for item in items:
        title = item.find_element(By.XPATH, './div/h5/a').text
        price = item.find_element(By.XPATH, './div/ul/li/span/span').text
        if title and price:
            print('{} - {}'.format(title, price))

except Exception as e:
    print(e)
finally:
    driver.quit()


ASUS B9440UA-0251A7200U (i5-7200/8G/256G SSD/W10P) - 32900
(商)Lenovo ThinkPad T470 20HDA00STW(i5-7200U/940MX-2G/1TB/W10P) - 39900
(商)HP X360 1030 G2(i7-7600U/8G*2/512GB SSD/FHD/W10Pro) - 68900
(商)HP 240 G6 (i5-7200U/14/4G/500GB/Win10) - 18900
DELL M7520(i7-7820HQ/Nvidia Quadro M2200M-4G/1TB+256GB/W10P/FHD)繪圖工作站筆電 - 89990
ASUS P2430UJ-0321A6200U (i5-6200U/4G/500G/920M-2G/Win10) - 22900
(商)Lenovo ThinkPad X1c 20HRA010TW(i7-7500U/256G SSD/W10P/FHD) - 59900
(商) HP Probook 430 G4(i5-7200U/4G DDR4/500GB/Win10) - 25900
(商)HP 240 G6 (i5-7200U/14/4G/500GB/Win10pro) - 23900
DELL M5520(i7-7820HQ/M1200M/512GB SSD/Win10 Pro/UHD)繪圖工作站筆電 - 98990
ASUS P2530UJ-0461A6200U (i5-6200U/8G/1TB/GeForce 920M-2G/W10P) - 23900
(商)Lenovo ThinkPad T470s 20HFA00ETW(i7-7600U/512G SSD/W10P) - 63900
(商)HP Probook 650 G3(i7-7600U/512GB SSD/AMD Radeon R7 M465 2GB/W10P) - 50900
(商)HP 240 G6 (i3-6006U/14/UMA/500G/W10DW7) - 17900
ASUS B9440UA-0251A7200U (i5-7200/8G/256G SSD/W10P) - 27900
ASUS P2530UJ-0271A6500U (i7-6500U/8G/1TB/920M-2G/FHD/Win10P) - 32900
(商)Lenovo ThinkPad Edge15 E570 20H5A037TW(i7-7500U/GTX 950M-2G/1TB/W10/FHD) - 34900
ACER TravelMate TMP238-M-77JQ (i7-6500U/8GB/256GB SSD/W7P+W10P) - 33800
ACER TravelMate TMX349-G2-M-53L8.(i5-7200U/8GB/256GB SSD/W10P) - 30500
DELL M7520(i7-7820HQ/Nvidia Quadro M1200M-4G/1TB/W10P/FHD)繪圖工作站筆電 - 76900
ASUS A550V-0203J6700HQ (i7-6700HQ/500G/GTX950M 2G獨顯/W10P) - 28900
(商)Lenovo ThinkPad X260 20F6A07QTW(i5-6200U/1TB/W10P) - 38900
ACER TravelMate TMP249-M-C1DV.(CM3855U/4GB DDR4/500GB/W10P) - 14990
ACER TravelMate TMP249-M-3142.(i3-6100U/4GB/500GB/W7P+W10P) - 17990
DELL M7510(i7-6820HQ/Nvidia Quadro M1000M-2G/1TB/W7P/FHD)繪圖工作站筆電 - 69900
ASUS B8230UA-0061A6500U (i7-6500U/512G SSD/W7P) - 44900
(商)Lenovo ThinkPad X270 20HNA00RTW (i5-7200U/1TB/W10P) - 41900
ACER TravelMate TMP446-M-54S0.(i5-5200U/4GB/500G/W7P+W10P) - 19900
ACER TravelMate TMP259-M-5726(i5-6200U/4GB/128GB SSD/W7P+W10P) - 26900
DELL Vostro 14 5000 (i5-7200U/4G/1TB/940MX-2G/W10/HD/Jingle Gold) - 23999