用 Selenium Python 下載圖片


我們可以使用 Python 中的 Selenium webdriver 下載影像。首先,我們應該使用 id、class、xpath 等定位符識別要下載的影像。

我們將使用open方法以寫入和二進位制模式開啟檔案(用wb表示)。然後使用screenshot_as_png方法捕獲我們希望捕獲的元素的螢幕截圖。

最後,必須將捕獲的影像寫入已開啟的檔案,方法是使用 write 方法。我們嘗試下載一個元素的影像,其程式碼如下:

語法

with open('Logo.png', 'wb') as file:
file.write(driver.find_element_by_xpath('//*[@alt="I"]').screenshot_as_png)

示例

from selenium import webdriver
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://tutorialspoint.tw/index.htm");
#open file in write and binary mode
with open('Logo.png', 'wb') as file:
#identify image to be captured
   l = driver.find_element_by_xpath('//*[@alt="Tutorialspoint"]')
#write file
   file.write(l.screenshot_as_png)
#close browser
driver.quit()

輸出

檔案 Logo.png 在專案資料夾中建立。

開啟檔案後:

更新於:02-Feb-2021

11K+ 瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告