在selenium中使用css选择器/xpath获取数据时遇到问题

2024-10-03 21:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过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)

Tags: 数据comurlreturntimedefwwwdriver
1条回答
网友
1楼 · 发布于 2024-10-03 21:27:30

所需数据位于iframe内部,因此在处理元素之前,需要切换到iframe:

driver.switch_to.frame(driver.find_element_by_class_name('position-ratios-iframe'))

还要注意,iframe中的数据是动态的,因此请确保使用Implicit/Explicit wait(使用time.sleep(5)IMHO不是最佳解决方案)

相关问题 更多 >