Python Selenium 单击 google "I agree"按钮

标签 python selenium web-crawler

我试图抓取一些谷歌数据,但我首先想点击谷歌弹出的“我同意”按钮。这是我用来执行此操作的脚本:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

search_question = input("Ask a question: ")

driver = webdriver.Chrome("*Your Webdriver location*")
driver.wait = WebDriverWait(driver, 5)

driver.get("https://google.com")

time.sleep(1)
agree = driver.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="introAgreeButton"]/span/span')))
agree.click()
# time.sleep(0.2)

search = driver.find_element_by_class_name("gLFyf")
search.send_keys(search_question)
search.send_keys(Keys.ENTER)
问题是 selenium 似乎没有找到按钮,因此我收到超时错误。 (我也尝试过 find_element_by_xpath ,但仍然无法正常工作)。

最佳答案

如果您在 devtools 检查器中向上滚动,您会注意到您的元素位于 iframe 中:
iframe in devtools
您需要先切换到该框架,单击按钮然后切换回默认内容(主页)


driver.get("https://google.com")

#active the iframe and click the agree button
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe")))
agree = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="introAgreeButton"]/span/span'))) 
agree.click()

#back to the main page
driver.switch_to_default_content()
这对我行得通。
仅供引用 - 页面上只有 1 个 iframe,这就是 xpath //iframe 的原因作品。如果有多个,您需要以更高的准确度识别它。

关于Python Selenium 单击 google "I agree"按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65286557/

相关文章:

python - 使用 pydantic json_decoders 解析不同的时间格式没有按预期工作

python - 'in fp' 和 'in fp.readlines()' 有什么区别?

testing - google-analytics.com 阻止我本地的测试用例

python - 是否有可能 "transfer"selenium.webdriver 和 requests.session 之间的 session

apache - 如何限制 Apache Nutch 2.3.1 抓取故事内容而不是边栏

python - 我如何使用 Beautifulsoup 获取 url 地址

python - 使用 Python 解析和渲染 Kinesis Video Streams 并获取输入帧的图像表示

python为类的每次调用获取新的随机名称

C# 通过实现的显式转换获取转换异常

apache - Solr 索引从 1.4.1 升级到 5.2.1