【问题标题】:Did not wait to load the site in selenium没有等待在硒中加载网站
【发布时间】:2019-02-12 23:33:57
【问题描述】:

我执行了:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
import time

print("Opening...")
driver = webdriver.Chrome()
driver.get('https://google.com')
driver.execute_script("window.open('https://www.yahoo.com');") #New tab
search = driver.find_element_by_xpath("//input[@type='text' and @id='uh-search-box']")
search.send_keys('Hello')

给我错误:

selenium.common.exceptions.NoSuchElementException:消息:没有这样的 元素:无法定位元素: {"method":"xpath","selector":"//input[@type='text' and @i d='uh-search-box']"}

这个错误是因为它没有在chrome中完成加载并执行进一步的代码......

如何摆脱它?

如何等待加载并执行进一步的脚本...(就像第一个标签一样,google.com)?

【问题讨论】:

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

尝试切换到新窗口如下:

current = driver.current_window_handle
driver.execute_script("window.open('https://www.yahoo.com');") #New tab
new_window = [window for window in driver.window_handles if window != current][0] # Get new tab ID
driver.switch_to.window(new_window) # Switch to new tab
search = driver.find_element_by_xpath("//input[@type='text' and @id='uh-search-box']")

【讨论】:

  • 我不知道他们为什么投了反对票,没有评论:stackoverflow.com/questions/52223642/…
  • 不知道。您可以查看this ticket,但似乎该解决方案不适用于最新的 Chromedriver 版本……那么当前问题呢?如果我的答案解决了,别忘了accept it
  • 但是我的driver.switch_to.window(driver.window_handles[0]) #First tab 代码不起作用(切换到上一个选项卡)....
  • 试试driver.switch_to.window(current)
  • 哦抱歉,误会评论错误,评论中的代码对我来说效果很好。我的评论是:每当我从 selenium 打开 chrome 时,它​​也会打开一个标签 (see image),为什么它打开了吗?如何阻止它?
猜你喜欢
  • 2017-02-06
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 2018-07-08
  • 2019-11-30
  • 2017-07-13
  • 1970-01-01
相关资源
最近更新 更多