【问题标题】:How to solve find_element_by_class_name() throwing "Unable to find element with class name '...'"?如何解决 find_element_by_class_name() 抛出“无法找到具有类名'...'的元素”?
【发布时间】:2017-07-11 02:59:04
【问题描述】:

网页(请参阅下面的driver.get())似乎有一个表,其中类名称为表。我似乎无法使用下面的代码找到它。

我的印象是我可以使用 Selenium 定位这些类型的 Javascript 元素。

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

driver.quit()
driver = webdriver.PhantomJS()

driver.get('http://investsnips.com/list-of-publicly-traded-micro-cap-diversified-biotechnology-and-pharmaceutical-companies/')


content = driver.find_element_by_css_selector('table.table')
x = driver.find_element_by_class_name("table")

我收到此错误(内容或 x 工作)

NoSuchElementException: Message: {"errorMessage":"Unable to find element with class name 'table'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"94","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:49464","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"class name\", \"value\": \"table\", \"sessionId\": \"a988f310-65da-11e7-a655-01f6986e9e41\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/a988f310-65da-11e7-a655-01f6986e9e41/element"}}
Screenshot: available via screen

【问题讨论】:

  • 您到底想定位哪个元素?
  • 请通过编辑将相关的 HTML 片段(通过开发工具提取;F12)添加到您的问题中。该链接是不稳定的,如果将来链接更改,您的问题将毫无用处。

标签: javascript python-3.x selenium


【解决方案1】:

iframe 中的表格。您必须在找到表格之前切换 iframe。请参阅下面的代码。

driver = webdriver.PhantomJS()

driver.get('http://investsnips.com/list-of-publicly-traded-micro-cap-diversified-biotechnology-and-pharmaceutical-companies/')

#Find the iframe tradingview_xxxxx and then switch into the iframe
iframeElement = driver.find_element_by_css_selector('iframe[id*="tradingview_"]')
driver.switch_to_frame(iframeElement)
#Wait for the table
waitForPresence = WebDriverWait(driver, 10)
waitForPresence.until(EC.presence_of_element_located((By.CSS_SELECTOR,'table.table'))
theTable = driver.find_element_by_css_selector('table.table')

【讨论】:

  • 我明白了。将对您的代码进行一些测试。非常感谢=)
  • 嗨,您是否正在为wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'table.table')) 中的wait 导入某些内容。我在您的代码中没有看到任何 wait 变量赋值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2022-10-14
  • 2020-03-05
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多