首页 > 解决方案 > 如何在硒(python)中处理谷歌隐私弹出窗口

问题描述

我对硒很陌生,我搜索了很多,但找不到我的问题的答案。我想打开火狐,去谷歌搜索一些东西。将所有内容存储在列表中并将其打印到我的控制台。

但是每次我用 selenium 打开 Firefox 时,都会打开一个弹出窗口,确认谷歌的隐私规定。我不知道如何关闭它。

这是我尝试过的:

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
import time

# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.maximize_window()

# Navigate to the application home page
driver.get("http://www.google.com")
main_page = driver.current_window_handle

time.sleep(3)

#Tried to find out in which browers window I am right now -> terminal says '19'
print('The actual browers window is: {}'.format(main_page))

driver.find_element_by_xpath("//*[@id='introAgreeButton']/span/span").click()

# get the search textbox
search_field = driver.find_element_by_id("lst-ib")
search_field.clear()

# enter search keyword and submit
search_field.send_keys("Flowers")
search_field.submit()

# get the list of elements which are displayed after the search
# currently on result page using find_elements_by_class_name method
lists= driver.find_elements_by_class_name("_Rm")

# get the number of elements found
print ("Found " + str(len(lists)) + " searches:")

# iterate through each element and print the text that is
# name of the search

i=0
for listitem in lists:
   print (listitem.get_attribute("innerHTML"))
   i=i+1
   if(i>10):
      break

# close the browser window
driver.quit()

标签: pythonseleniumpopupalertprivacy

解决方案


Google 隐私弹出窗口包含在 iframe 中。您必须切换到 iframe,然后寻找接受(或拒绝)按钮。像这样

wait = WebDriverWait(driver, 5)
     iframe = wait.until(EC.element_to_be_clickable([By.CSS_SELECTOR, '#cnsw > iframe']))
    driver.switch_to.frame(iframe)

然后在 iframe 中,查找 Accept 按钮并单击它。


推荐阅读