首页 > 解决方案 > How to handle google website data security pop up?

问题描述

I am new to Python and to Selenium and was running into a problem using this simple program:

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:/Users/Marc/Desktop/Chromedriver/chromedriver.exe")

#open google
driver.get("https://www.google.de")

#search for test
driver.find_elements_by_name("q").send_keys("test")
driver.find_elements_by_name("btnK").click()

It just should open the google webpage in Chrome and initiate a search for the word "test". However when opening the webpage a new element pops up informing about data security and cookies and the search is not executed -> "AttributeError: 'list' object has no attribute 'send_key". (As far as I understand it the reason for the pop up is due to the fact that the browser run by chromedriver doesn't use any of the preexisting cookies.)

How can I solve this? I already tried to us the switch_to_alert method but it didn't work out.

edit: For me it is not about the google website itself but how to deal with it in general as it could occur on other websites as well. Why can't I perform an action on this element? or how can I?

Thanks for your help in advance!

标签: pythonselenium-chromedriver

解决方案


如果您在浏览器中签入开发工具,则 Google 网站上的弹出窗口位于 iframe 中。因此,您只需要像这样切换到 iframe 的上下文:

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:/Users/Marc/Desktop/Chromedriver/chromedriver.exe")

#open google
driver.get("https://www.google.de")

#search for test
iframe = driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(iframe)
elt = driver.find_elements_by_class_name("CwaK9")
elt[2].click()
driver.find_elements_by_name("q")[0].send_keys("test")
driver.find_elements_by_name("btnK").click()

推荐阅读