爬蟲5-Seleium(如何使用)

 


為什麼需要用Seleiun這樣的網站模擬器去叫起一個Browser呢?因為有些資料為了防止爬蟲,如果不是透過瀏覽器的方式叫起,將會無法trigger有拿資料的 function ,這是目前拿隱藏資料最快的解決辦法

裝好套件

pip install selenium

我們必須去載chromedriver 然後放在我們專案的路徑下就可以使用了

範例:

情境是,某網站的Canvas是被Function 驅動後才產生的,所以直接發Request 返回是找不到Canvas這個節點


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--disable-notifications")

chrome = webdriver.Chrome('./chromedriver/chromedriver.exe', chrome_options=options)

chrome.get(response._url)

# check we had canvas to insert data

canvas = chrome.find_element_by_xpath("//canvas").size != 0
print(canvas)

透過Seleium叫起瀏覽器就可以去看Canvas 是否有被產生出來

小結:

透過瀏覽器的方式,以爬蟲速度來講是很慢的一件事情,接下來會去尋求更快的方法,如果有新的方法,會在此篇文章更新的






留言

這個網誌中的熱門文章

Vue那些我踩過的坑(Vuex-TypeScript)

Vue(Vue3取代 Vuex?)

前端優化效能-1(lazy-img)