我正在使用 selenium 制作一个 python 程序来自动与网页交互。 Selenium的版本是4.1.3,Chrome的版本是124。 当我进入页面时出现cookies弹出窗口,并且我找不到使用代码单击的按钮时,就会出现问题。我在这里尝试过在 StackOverflow 解决方案中找到的方法,但它不起作用:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
s = Service(r"chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument("--disable-cookies")
# start driver
driver = webdriver.Chrome(service=s, options=options)
# go to page
driver.implicitly_wait(10)
driver.get('https://deepai.org/machine-learning-model/fantasy-world-generator')
# find accept cookies button
button= driver.find_element_by_xpath('//*[@id="notice"]/div[3]/div[2]/button')
button.click()
# find textarea by placeholder
textarea = driver.find_element_by_css_selector('textarea[placeholder="Enter your prompt"]')
# enter a monster in textarea
textarea.send_keys('A monster')
# button search
hdButton = driver.find_element_by_id("modelHdButton")
hdButton.click()
button = driver.find_element_by_id("modelSubmitButton")
button.click()
# close controller
driver.quit()
我使用chrome控制台F12获取元素的路径,复制XPath选项,所以应该不会错。
我尝试过使用 JSPath 和选项列表中的其他路径,但它也不起作用。 我还尝试停用网络驱动程序的选项参数,仅放置
driver = webdriver.Chrome(service=s)
。
它应该能够单击该按钮,或者至少找到它,但它两者都做不到。
这可能听起来很愚蠢,但我发现问题在于 cookie 位于 iframe 内,它似乎被视为与页面不同的文档,至少在路由级别如此。 我所要做的就是使用这个功能:
driver.switch_to.frame("iframe_id")
。
并使用正常路径。