如何从硒对象中提取文本?

时间:2019-11-16 14:37:12

标签: python selenium

我的代码登录到我的Fidelity帐户,然后找到一个元素。我可以找到Selenium对象,但是我想提取其中包含我的投资组合余额的文本。当我打印对象时,代码可以正常工作,但是我无法从中获取文本或余额。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


def fidelity_check():
    options = webdriver.ChromeOptions()
    options.add_argument("start-maximized")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("detach", True)
    # options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\Notebook\Documents\chromedriver.exe')
    driver.get("https://www.fidelity.com/")
    WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#userId-input"))).send_keys(
        "MYUSERID")
    driver.find_element_by_css_selector("input#password").send_keys("MYPASSWORD")
    driver.find_element_by_css_selector("button#fs-login-button").click()

    try:
        element_present = EC.presence_of_element_located((By.XPATH, '// *[ @ id = "tabContentSummary"]'))
        WebDriverWait(driver, 10).until(element_present)
        print(element_present)
    except TimeoutError:
        print("Page Not Loaded.")

这是结果: selenium.webdriver.support.expected_conditions.presence_of_element_located对象位于0x035EFE10

这是检查元素的结果:

<span class="ledger--section-total js-total-balance-value">$X.XX</span>

我尝试了以下操作,但不起作用。

element_present.text()
# And I tried:
element_present.text

都不行。

2 个答案:

答案 0 :(得分:1)

您必须在WebDriverWait中的变量中分配值,然后获取文本。您已经完成打印了硒对象。

element_present = EC.presence_of_element_located((By.XPATH, '// *[ @ id = "tabContentSummary"]'))
element=WebDriverWait(driver, 10).until(element_present)
print(element.text)

EDIT

element_present = EC.visibility_of_element_located((By.XPATH, '// *[ @ id = "tabContentSummary"]'))
element=WebDriverWait(driver, 20).until(element_present)
print(element.text)

OR

element_present = EC.element_to_be_clickable((By.XPATH, '// *[ @ id = "tabContentSummary"]'))
element=WebDriverWait(driver, 20).until(element_present)
print(element.text)

答案 1 :(得分:1)

请尝试以下解决方案

l1 = [{'company': 'XYZ', 'url': '/xyz', 'industry': 'Utilities', 'sector': 'Conventional electricity'}, {...}]
l2 = [{'url': '/xyz', 'industry': ['Electric utility'],  'website': ['xyz.com']}, {...}]