无法单击按钮 - Python / Selenium & bs4



我试图点击一个按钮,已经尝试了几种不同的方法,但都没有成功。

方法1:

WebDriverWait(driver, 20).until(EC.invisibility_of_element((By.CLASS_NAME, 'sc-gsDKAQ fWOgSr')))
driver.execute_script("arguments[0].click();", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, 'sc-gsDKAQ fWOgSr'))))

方法2:

driver.find_element(by=By.CLASS_NAME, value='sc-gsDKAQ fWOgSr').click()

方法3:

btn = driver.find_element(by=By.CLASS_NAME, value='sc-gsDKAQ fWOgSr')
btn.click()

错误消息:

M1:超时

M2:无SuchElementException

M3:无SuchElementException

我用Xpath做了同样的尝试,但没有成功。在过去有另一个错误,该错误指出";字符串"无法与交互。

该元素位于#shadow root元素中,因此访问起来有点麻烦。此外,页面似乎会对鼠标移动做出反应(并且只有在检测到一些鼠标移动后才会加载(。以下代码似乎有效:安装程序在Linux上,但您可以根据自己的情况进行调整,只需观察导入和定义浏览器后的部分:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
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("--no-sandbox")
chrome_options.add_argument('disable-notifications')
import time as t

webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
actions = ActionChains(browser)
url = 'https://www.immobilienscout24.at/regional/wien/wien/wohnung-kaufen'
browser.get(url) 
page_title = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a[title='Zur Homepage']")))
actions.move_to_element(page_title).perform()
parent_div = WebDriverWait(browser, 20000).until(EC.presence_of_element_located((By.ID, "usercentrics-root"))) 
shadowRoot = browser.execute_script("return arguments[0].shadowRoot", parent_div)
try:
button = WebDriverWait(shadowRoot, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']"))) 
button.click()
print('clicked')
except Exception as e:
print(e)
print('no click button')

这将点击按钮,并在终端中打印:

clicked

相关内容

  • 没有找到相关文章

最新更新