Mike的Python學院

網頁資料擷取與分析 Python、Python網路爬蟲、網路爬蟲、Selenium、Python

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/15

Python使用Selenium開發動態網頁爬蟲的技巧

Q: Python的Selenium套件有什麼功能?
Selenium套件被設計於自動化測試,來模擬使用者的動作,進行登入後爬取資料或滾動卷軸,並且能夠執行JavaScript程式碼,這些就是Selenium與BeautifulSoup套件最大不同的地方。對於開發Python動態爬蟲來說,就可以結合Selenium套件以上的特點,讓網頁動態載入資料後,再利用BeautifulSoup套件簡潔的方法(Method),將所需的資料爬取下來。
Q: 要怎麼開始使用Selenium套件?
Python的Selenium套件安裝指令如下:
$ pip install selenium
除此之外,要讓Selenium套件能夠自動開啟瀏覽器,就需要安裝對應的Webdriver(驅動程式),本文將以Chrome瀏覽器來做示範。前往Python套件儲存庫PyPI(Python Package Index),輸入Selenium進行查詢,並且手動安裝相對應版本的瀏覽器驅動程式。
Q: Selenium套件如何請求網頁?
首先,建立webdriver物件,傳入所下載的「瀏覽器驅動程式路徑」,就可以透過get()方法,前往要爬取的網頁網址。如下範例:
from selenium import webdriver
chrome = webdriver.Chrome('./chromedriver')
Q: Selenium套件如何定位網頁上的資料元素?
Selenium套件的定位元素方法非常多,可以參考Selenium套件的官方文件( https://selenium-python.readthedocs.io/locating-elements.html ),這邊以常使用的find_element_by_id()方法(Method)為例,如下:
email = chrome.find_element_by_id("email")
password = chrome.find_element_by_id("pass")
Q:Selenium套件如何模擬使用者輸入資料?
透過Selenium套件的send_keys()方法,就可以模擬使用者輸入資料,如下範例:
email = chrome.find_element_by_id("email")
password = chrome.find_element_by_id("pass")
email.send_keys('example@gmail.com')
password.send_keys('*****')
password.submit()
Q: Selenium套件如何執行JavaScript程式碼?
本文以滾動捲軸這個動作,來分享如何利用Selenium套件的execute_script()方法,來執行JavaScript程式碼,如下範例:
chrome = webdriver.Chrome('./chromedriver', chrome_options=options)
email = chrome.find_element_by_id("email")
password = chrome.find_element_by_id("pass")
email.send_keys('example@gmail.com')
password.send_keys('*****')
password.submit()
time.sleep(3)
for x in range(1, 4):
chrome.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(5)
範例中,使用Python的迴圈,執行滾動捲軸3次,每滾動一次就暫停執行程式碼5秒,讓Facebook載入更多的文章。
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/05/python-selenium-scraper.html )網站觀看更多精彩內容。
1 0 397 0