硒点击不适用于纳斯达克网站中的链接

时间:2019-08-21 06:44:27

标签: python selenium web-scraping beautifulsoup

因此,问题非常简单明了。在链接中 https://www.nasdaq.com/symbol/iff/revenue-eps

我想使用硒单击链接“ Previous 3 Years”,但这似乎不起作用。

下面的代码是我尝试的。它适用于大多数网页,但由于某些原因而不适用。我试图通过它包含的文本找到该元素,然后单击它。

link = driver.find_element_by_link_text('Previous 3 Years')
link.click()

当我最终运行它时,这是我收到的错误消息:

Traceback (most recent call last):
  File "writeTest.py", line 68, in <module>
    link = driver.find_element_by_link_text('Previous 3 Years')
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 428, in find_element_by_link_text
    return self.find_element(by=By.LINK_TEXT, value=link_text)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Previous 3 Years"}
  (Session info: headless chrome=76.0.3809.100)

有人可以告诉我这里似乎是什么问题吗?

2 个答案:

答案 0 :(得分:0)

您的对象位于iframe中,因此需要对其进行切换,您需要这样编写代码

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


WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"#frmMain")))

link = driver.find_element_by_link_text('Previous 3 Years')
link.click()

用于切换

driver.switch_to.default_content()

答案 1 :(得分:0)

因为目标元素位于iframe内部。这就是为什么找不到它的原因,因为您正在处理主要内容。下面的代码将为您工作:

from selenium.webdriver.common.by import By

revenue_table = driver.find_element(By.ID, value="frmMain")
driver.switch_to.frame(revenue_table)
# Your code
link = driver.find_element_by_link_text('Previous 3 Years')
link.click()

# You can switch back to the main content by below code:
driver.switch_to.default_content()