Python 網路爬蟲

[Python] Selenium Little Known Tips 你可能不知道的 Selenium 技巧

turned on computer monitor displaying text

有些 Selenium 功能或技巧,沒用過不知道應該要這樣寫,或是比較不直覺的做法;因為都比較零碎,我將它整理到這篇。

Scroll Page 滾動頁面

You might be thinking, isn’t this what execute_script does? However, on some web pages, there are indeed situations where it cannot take effect. At this time, another method can be used:

你可能會想說,這不就是用 execute_script 來處理嗎? 但是在某些網頁上確實有遇到無法生效的情況,此時還可以用另一種作法:

driver.find_element('xpath', '//body').send_keys(Keys.END)  # Scroll to the bottom 滑到當前頁面最底部
driver.find_element('xpath', '//body').send_keys(Keys.HOME)  # Scroll to the top 滑到當前頁面最上面

Methods to scroll page 滾動頁面的做法

  1. Scroll to the specified height/current maximum depth 滑到指定高度/當前最大深度
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

2. Scroll to the specified object 滑到指定物件處

elem = driver.find_element_by_xpath("//div[@id='root']/div")
driver.execute_script("arguments[0].scrollIntoView(true);", elem)

3. Scroll Pages with Keys 利用 Keys 移動頁面

driver.find_element('xpath', '//body').send_keys(Keys.END)
driver.find_element('xpath', '//body').send_keys(Keys.HOME)
%d 位部落客按了讚: