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

有些 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)

Related Posts

[PyTorch] 使用 torch.distributed 在單機多 GPU 上進行分散式訓練

Finetune 語言模型所需要的 GPU memory 比較多,往往會需要我們能夠利用到多顆 GPU 的資源。今天這篇文章會說明 DataParallel 和 DistributedDataParallel + DistributedSampler 兩種進行模型分散式訓練的方式。

經典 NLP 任務標籤生成:串接非官方 ChatGPT API

這篇文章紀錄我串接非官方 ChatGPT API 「試圖」取得 NLP 資訊抽取任務標籤的過程。結論是…

發表迴響

%d 位部落客按了讚: