Selenium无法使用xpath找到元素,但我可以手动找到它

时间:2019-05-07 08:25:38

标签: selenium selenium-webdriver python-3.6

我需要使用xpath查找此图像元素。 Selenium会引发NoSuchElementException异常,但是当网页仍然打开时,我可以通过将xpath粘贴到开发人员工具的find函数中来找到该元素。

我尝试了隐式和显式等待,正常的睡眠命令,并在for循环中连续搜索元素(8小时)

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://captcha.com/demos/features/captcha-demo.aspx')

WebDriverWait(driver, 20).until(
  EC.presence_of_element_located((By.XPATH,'//*[@id="c_captchademo_samplecaptcha_CaptchaImage"]')))

img = driver.find_element_by_xpath('//*[@id="c_captchademo_samplecaptcha_CaptchaImage"]')

print(img)

1 个答案:

答案 0 :(得分:0)

您必须先切换到iframe才能访问验证码。请尝试以下代码。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://captcha.com/demos/features/captcha-demo.aspx')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"demo_frame")))
image=WebDriverWait(driver, 20).until(
  EC.element_to_be_clickable((By.XPATH,'//img[@id="c_captchademo_samplecaptcha_CaptchaImage"]')))
print(image.get_attribute('alt'))