我试图通过python使用selenium从下面的链接中提取数据: www.oanda.com
但我得到一个错误,“无法定位元素”。在浏览器控制台中,我尝试使用以下Css选择器:
document.querySelector('div.position.short-position.style-scope.position-ratios-app')
这个querySelector返回浏览器控制台中第一行的短百分比数据(对于这个测试),但是当我在下面的python脚本中使用这个选择器时,它会给我一个错误,“找不到元素”或者有时是空字符串。 如果有任何解决方案,请向我建议。将不胜感激,谢谢:)
# All Imports
import time
from selenium import webdriver
#will return driver
def getDriver():
driver = webdriver.Chrome()
time.sleep(3)
return driver
def getshortPercentages(driver):
shortPercentages = []
shortList = driver.find_elements_by_css_selector('div.position.short-position.style-scope.position-ratios-app')
for elem in shortList:
shortPercentages.append(elem.text)
return shortPercentages
def getData(url):
driver = getDriver()
driver.get(url)
time.sleep(5)
# pagesource = driver.page_source
# print("Page Source: ", pagesource)
shortList = getshortPercentages(driver)
print("Returned source from selector: ", shortList)
if __name__ == '__main__':
url = "https://www.oanda.com/forex-trading/analysis/open-position-ratios"
getData(url)
所需数据位于iframe内部,因此在处理元素之前,需要切换到iframe:
还要注意,iframe中的数据是动态的,因此请确保使用Implicit/Explicit wait(使用
time.sleep(5)
IMHO不是最佳解决方案)相关问题 更多 >
编程相关推荐