[英]check if "show more" link has already been pressed python selenium
我有一個問題,我正在運行一個 while 循環,有時網頁會重新加載,而有時它不會。 如果重新加載,那么我必須按下顯示更多以向下滾動。 我試圖通過編寫以下 function 來做到這一點。
def Press_Show_more(driver):
# time.sleep(1)
# Press once on the "show more" which will lead to infinit loop
path1 = "/html/body/div[1]/div/div[2]/studio-page/div/section/div/div/studio-video-results/video-results/div[3]/items-list/div/div[2]/div[2]/button"
el = Check_If_element_exist_by_path(driver, path1)
if 'WebElement' in str(type(el)):
el.click()
driver.find_element(By.TAG_NAME, 'body').send_keys(
Keys.CONTROL + Keys.HOME)
else:
print('The show more element does not exist')
這在 while 循環中對我來說效果不佳。 有什么幫助嗎? 這是編寫代碼的最佳方式嗎?
def Check_If_element_exist_by_path(driver, path2):
try:
el = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, path2)))
return el
except Exception as e:
print(f"The non-existant path: {path2}")
我不知道你是如何在這里實現Check_If_element_exist_by_path
方法的,但我認為你可以使用WebDriverWait
ExpectedConditions
來等待元素存在可見性。 另外,我建議使用返回 web 元素列表的方法,因此如果存在所需元素,則返回的列表將是非空的,並且將被if
解釋為 Boolean True,否則它將返回一個空列表它將被解釋為 Boolean 錯誤。 如下所示:
actions = ActionChains(driver)
def Press_Show_more(driver):
# time.sleep(1)
# Press once on the "show more" which will lead to infinit loop
path1 = "/html/body/div[1]/div/div[2]/studio-page/div/section/div/div/studio-video-results/video-results/div[3]/items-list/div/div[2]/div[2]/button"
el = WebDriverWait(browser, 20).until(EC.presence_of_all_elements_located((By.XPATH, path1)))
if el:
actions.move_to_element(el[0]).perform()
time.sleep(0.5)
el[0].click()
driver.find_element(By.TAG_NAME, 'body').send_keys(
Keys.CONTROL + Keys.HOME)
else:
print('The show more element does not exist')
您將需要以下導入:
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.common.action_chains import ActionChains
import time
另外,你應該改進你的定位器
檢查元素是否存在的更簡單方法是使用.find_elements()
並檢查空列表。
def Press_Show_more(driver):
path1 = "/html/body/div[1]/div/div[2]/studio-page/div/section/div/div/studio-video-results/video-results/div[3]/items-list/div/div[2]/div[2]/button"
el = driver.find_elements(By.XPATH, path1)
if len(el) > 0:
el[0].click()
driver.find_element(By.TAG_NAME, 'body').send_keys(
Keys.CONTROL + Keys.HOME)
else:
print('The show more element does not exist')
由於檢查已大大簡化,因此您不需要Check_If_element_exist_by_path()
方法。
我要感謝@Prophet,他幫助我找到了這個解決方案
def Press_Show_more(driver):
# Press once on the "show more" which will lead to infinit loop
path1 = "/html/body/div[1]/div/div[2]/studio-page/div/section/div/div/studio-video-results/video-results/div[3]/items-list/div/div[2]/div[2]/button"
el = WebDriverWait(driver, 20).until(
EC.presence_of_all_elements_located((By.XPATH, path1)))
# Check if element is clickable
try:
el[0].click()
except WebDriverException:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.