gpt4 book ai didi

python - 当元素为 data-testid 时如何处理弹出窗口 "Accepting all cookies"- 在 Python 中使用 Selenium

转载 作者:行者123 更新时间:2023-12-03 08:12:57 27 4
gpt4 key购买 nike

所以我开始了一个新项目来帮助我工作的一家有关太阳能电池板的中型企业......基本上我想用 Selenium 从特定网站获取数据并在我的 GUI 上看到它的另一个 friend 我的处理它......我的主要问题是当我使用 python 打开带有 selenium 的网站时,弹出 cookie“接受所有 cookie”已显示,因为我是 selenium 的新手,所以我不知道如何处理我已经搜索了大约 2 天关于这个问题的信息,但我尝试的任何方法都不起作用,所以我认为我是一个特例 xD...

这是你们需要知道的来帮助我的一切:

► 网址 ◄

https://www.kostal-solar-portal.com/#/

► 图片 ◄

[图1] = /image/ZR89s.png |

[图2] = /image/Zirft.png |

► 代码 ◄

`driver = webdriver.Chrome(PATH)

driver.implicitly_wait(10)

kostal_url = "https://www.kostal-solar-portal.com/#/"

driver.get(kostal_url)

driver.find_element_by_xpath('//*[@id="usercentrics-root"]//div/div/div[1]')
cookies = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH,)))
cookies.click()`

► 错误 ◄

Traceback (most recent call last):
File "c:/Users/Hp/Desktop/ΜΑΚΗΣ/App/open_websites.py", line 27, in <module>
driver.find_element_by_xpath('//*[@id="usercentrics-root"]//div/div/div[1]')
File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1246, in find_element
'value': value})['value']
File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="usercentrics-root"]//div/div/div[1]"}

最佳答案

元素全部接受#shadow-root (open)内.

kostal


解决方案

要单击全部接受,您必须使用 shadowRoot.querySelector()您可以使用以下 Locator Strategy :

  • 代码块:

    driver.get("https://www.kostal-solar-portal.com/#/")
    time.sleep(5)
    element = driver.execute_script("""return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")
    element.click()

引用文献

您可以在以下位置找到一些相关讨论:

关于python - 当元素为 data-testid 时如何处理弹出窗口 "Accepting all cookies"- 在 Python 中使用 Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70347087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com