python - 如何在硒(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()
解决方案
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 按钮并单击它。
推荐阅读
- resnet - 在 ResNet TensorFlow 中切换层
- html - 使用 renderUI 更改页面上的输入顺序
- resteasy - JaxRsSecurityConfig 与 quarkus-spring-data-rest 和 quarkus-resteasy-reactive 冲突
- sql - SQL-忽略空值而不按顺序打印
- c++ - Qt Creator C++ 错误:找不到匹配“ui_mainwindow.h”的文档
- angular - Angular中使用Typescript的常量变量与枚举类型
- google-cloud-platform - 谷歌云存储桶用于没有域的静态服务
- wsl-2 - WSL 2,React 不通过文件更改重新加载?
- android - 如何在 Jetpack Compose 中绘制一些在 Сanvas 上旋转的元素?
- javascript - 页面加载后,Safari 仅加载一次带有 javascript 和 css 的动画