我正在嘗試截取長頁面的不同元素(在不同部分)的螢屏截圖。我拍攝的第一個螢屏截圖位于頁面頂部附近,并且沒有被截斷:

然而,一旦 selenium 必須滾動來截取元素的螢屏截圖,螢屏截圖就會被截斷:

我很確定會發生這種情況,因為 selenium 滾動的距離不足以使整個元素暴露,因此截取的螢屏截圖不完整——但我不知道如何解決這個問題。任何幫助將不勝感激。以下是我目前的代碼(截屏元素發生在最后幾行代碼中):
from time import sleep
from os import chdir
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
option = webdriver.ChromeOptions()
option.add_experimental_option("excludeSwitches", ["enable-automation"])
option.add_experimental_option('useAutomationExtension', False)
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")
option.add_experimental_option("detach", True)
option.add_experimental_option("prefs", {
"profile.default_content_setting_values.notifications": 2
})
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=option)
driver.get("https://www.reddit.com/r/AskReddit/")
#Show top reddit posts on the subreddit
topButton = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[4]/div[1]/div[1]/div[2]/a[3]")))
topButton.click()
#Topic
topic = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[4]/div[1]/div[4]/div[2]')))
topic.click()
sleep(1)
topicText = driver.find_element(By.XPATH, '/html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[1]/div/div[3]/div[1]/div/h1').text
topicPicture = driver.find_element(By.XPATH, '/html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[1]/div')
chdir(r'C:\Users\jack_l\Documents\PLAYING_WITH_REDDIT\currentVideo')
topicPicture.screenshot('topic.png')
#Comments
comment = ''
verified = 0
counter4 = 0
while(verified <= 10):
try:
comment = driver.find_element(By.XPATH, '/html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[5]/div/div/div/div[' str(counter4) ']')
except Exception:
counter4 = counter4 1
else:
if 'level 1' in comment.text:
comment.screenshot('comment ' str(verified) '.png')
verified = verified 1
counter4 = counter4 1
uj5u.com熱心網友回復:
在 try 塊中定義comment. 它所做的只是向下滾動,使 web 元素comment位于頁面的中心。這樣就可以得到一個完整的截圖
try:
comment = driver.find_element(By.XPATH, '...')
driver.execute_script('arguments[0].scrollIntoView({block: "center"});', comment)
except:
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478012.html
標籤:Python html 硒 硒网络驱动程序 硒铬驱动程序
