【问题标题】:Python web scraping on Morningstar.com through Selenium + XPath通过 Selenium + XPath 在 Morningstar.com 上进行 Python 网页抓取
【发布时间】:2018-11-05 08:55:16
【问题描述】:

我正在尝试使用 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 代码中找到了正确的模式。

【问题讨论】:

  • 没有错误信息,它只是返回两个空列表

标签: python html selenium xpath web-scraping


【解决方案1】:

由于 iFrame(本质上是网页中的网页),您遇到了问题。要访问 iFrame 中的项目,您需要先切换到它。

``` 
Define path of iFrame desired. I used a @src contains 
since there are multiple iFrames on the page.
``` 
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()

【讨论】:

  • 感谢 W Stokvis 的帮助,但不幸的是,您的代码无法在我的 PC 上运行。这是我看到的错误消息:selenium.common.exceptions.WebDriverException: Message: unknown error: call function result missing 'value' (Session info: chrome=66.0.3359.181) (Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a) ,platform=Windows NT 10.0.16299 x86_64)
  • 您的 chromedriver 可能有问题,您可能需要更新它。你可以在这里找到一些答案:github.com/webdriverio/webdriverio/issues/2631
  • 感谢一百万!问题确实是我的 chromedriver 旧版本,现在可以正常工作了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2021-05-08
  • 2018-07-20
  • 2020-03-13
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多