我正在尝试使用Selenium库在Morningstar.com上抓取与共同基金和ETF相关的数据,但以下代码不起作用:
from selenium import webdriver
driver = webdriver.Chrome()
link = "https://www.morningstar.com/etfs/bats/maga/quote.html"
driver.get(link)
TNA = driver.find_elements_by_xpath('//td[@class="gr_table_colm2b"]//span[@id="NAV"]')
print(TNA)
currency = driver.find_elements_by_xpath('//span[@class="gr_text3" and @id="navCurrency"]')
print(currency)
driver.close()它有什么问题?我已经检查过Selenium实际上是通过远程打开Chrome的,并且XPath在HTML代码中找到了正确的模式。
发布于 2018-05-26 08:30:44
你有问题是因为iFrames (本质上是网页中的一个网页)。要访问iFrame中的项目,您需要先切换到它。
定义所需iFrame的路径。我使用了@src包含
因为页面上有多个iFrames。
iframe = driver.find_element_by_xpath("//iframe[contains(@src,'.com/quote')]")
driver.switch_to.frame(iframe);
# I added the text part since I figured that was what you ultimately wanted.
TNA = driver.find_elements_by_xpath('//td[@class="gr_table_colm2b"]//span[@id="NAV"]')[0].text
print(TNA)
currency = driver.find_elements_by_xpath('//span[@class="gr_text3" and @id="navCurrency"]')[0].text
print(currency)
27.79
USD假设您想切换回原始页面,请使用以下代码。
driver.switch_to.default_content()https://stackoverflow.com/questions/50537982
复制相似问题