我正在尝试从无限滚动website
中提取链接这是我向下滚动页面的代码
driver = webdriver.Chrome('C:\\Program Files (x86)\\Google\\Chrome\\chromedriver.exe')
driver.get('http://seekingalpha.com/market-news/top-news')
for i in range(0,2):
driver.implicitly_wait(15)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(20)
我的目标是从此页面中提取特定链接。使用class =" market_current_title"和HTML如下:
<a class="market_current_title" href="/news/3223955-dow-wraps-best-week-since-2011-s-and-p-strongest-week-since-2014" sasource="titles_mc_top_news" target="_self">Dow wraps up best week since 2011; S&P in strongest week since 2014</a>
当我使用
时URL = driver.find_elements_by_class_name('market_current_title')
我最终得到的错误是&#34;陈旧元素引用:元素未附加到页面文档&#34;。然后我试了
URL = driver.find_elements_by_xpath("//div[@id='a']//a[@class='market_current_title']")
但它说没有这样的链接! 你对解决这个问题有任何想法吗?
答案 0 :(得分:1)
您可能正在尝试与已更改的元素进行交互(可能是滚动和关闭屏幕上方的元素)。请尝试this answer,了解如何克服这个问题。
这是一个片段:
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as ui
# return True if element is visible within 2 seconds, otherwise False
def is_visible(self, locator, timeout=2):
try:
ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
return True
except TimeoutException:
return False