Python + 硒超时异常

Python + Selenium TimeoutException

这是我第一次使用 Python 和 Selenium。代码的第一部分有效,但是当它转到第二页时,它永远找不到任何元素。如果我翻转代码并使其首先转到第二个站点,它就可以工作。我在这里做错了什么?我尝试了 xpath,CSS_Selector、Class_Name 似乎没有任何效果。这是我得到的错误:

回溯(最后一次调用): 文件“C:\Users\dresd\PycharmProjects\Test2\main.py”,第 20 行,位于 click_Register = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap")).click() 文件“C:\Users\dresd\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py”,第 89 行,直到 引发 TimeoutException(消息、屏幕、堆栈跟踪) selenium.common.exceptions.TimeoutException:消息:

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

driver = webdriver.Chrome ("C:/chromedriver.exe")

driver.get("https://10minutesemail.net/")

Copy_Email = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.ID, "copyEmailAddress"))).click()

time.sleep(10)

driver.execute_script("window.open('https://quora.com/','_blank')")

click_Register = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap"))).click()

name = driver.find_element(By.NAME, "profile-name")
email = driver.find_element(By.ID, "email")

name.send_keys("Jackson Fuller")

提前致谢!

您必须将驱动程序切换到新打开的选项卡。
否则焦点将保留在第一个浏览器 window.
TimeoutException 实际上意味着 Selenium 无法通过传递的定位器定位元素。
另外你用的定位器不好。
试试这个:

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

driver = webdriver.Chrome ("C:/chromedriver.exe")

driver.get("https://10minutesemail.net/")

Copy_Email = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.ID, "copyEmailAddress"))).click()

time.sleep(10)

driver.execute_script("window.open('https://quora.com/','_blank')")

driver.switch_to.window(driver.window_handles[1])
click_Register = WebDriverWait(driver, 20).until(
    EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap"))).click()

name = driver.find_element(By.NAME, "profile-name")
email = driver.find_element(By.ID, "email")

name.send_keys("Jackson Fuller")