跳过accept cookie,第二次循环SeleniumPython



我有一个脚本,它从谷歌图像中获取图像,然后将其粘贴到某个地方。当启动脚本时,它会按照预期做所有事情,包括接受";在你继续谷歌";饼干弹出。当脚本第二次进入循环时,谷歌cookie弹出窗口不再显示,所以我想我必须跳过这些步骤才能接受cookie。这就是我尝试过的

def get_image(title):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[2])
driver.get('https://www.google.com/imghp?hl=EN')
time.sleep(10)
while True:
try:
driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[3]/span/div/div/div/div[3]/div[1]/button[2]').click()
except TimeoutException as e:
print(e)
continue
else:
Rest of the script...

当脚本第二次运行时,它显示此错误-raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: {Alert text : Message: unexpected alert open: {Alert text : }

Cookie的完整XPATH接受全部按钮-/html/body/div[3]/div[3]/span/div/div/div/div[3]/div[1]/button[2]/div

您可以添加一个简单的检查,无论它是像这样的接受cookie页面

if driver.title.startswith('Before'):
driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[3]/span/div/div/div/div[3]/div[1]/button[2]').click()

最新更新