我找不到点击此页面上所有带有文本“更多”的按钮的方法 (https://religiondatabase.org/browse/regions)。我尝试了以下方法。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
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
chrome_options = Options()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.maximize_window()
driver.get('https://religiondatabase.org/browse/regions')
# Wait for the page to load
wait = WebDriverWait(driver, 10)
# Find all buttons containing the text "more"
buttons = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//button[contains(text(), 'more')]")))
print(buttons)
actions = ActionChains(driver)
for button in buttons:
actions.click(button).perform()
此方法单击第一个按钮,然后对于下一个按钮,我收到错误消息:
Message: move target out of bounds
为了解决这个问题,我尝试使用坐标点击并使用 javascript 滚动到视图中,如下所示:
for button in buttons:
coordinates = button.location_once_scrolled_into_view # returns dict of X, Y coordinates
driver.execute_script('window.scrollTo({}, {});'.format(coordinates['x'], coordinates['y']))
button.click()
这导致了以下错误:
Element is not clickable at point(x,y)
我还尝试按照许多 stackoverflow 帖子的建议使用 javascript 执行点击,但仍然没有运气:
for i in range(len(buttons)):
buttons = driver.find_elements(By.XPATH, "//button[contains(text(), 'more')]")
button = buttons[i]
driver.execute_script("arguments[0].click();", button)
这给出了以下错误:
Message: stale element reference: element is not attached to the page document