简体   繁体   中英

Can't get data-value out of element with selenium

In my code, i want to get a data-value out of text. My code is this:

    driver = webdriver.Chrome(chrome_options=chrome_options, executable_path="chromedriver.exe")
    driver.get('https://www.google.nl')
    accept = driver.find_element("xpath",'//*[@id="L2AGLb"]/div')
    accept.click()
    box =     driver.find_element("xpath",'/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input')
    box.send_keys("placeholder")
    box.send_keys(Keys.ENTER)
    for x in AmountInputFinal:
        close = driver.find_element("xpath", '/html/body/div[4]/div[2]/form/div[1]/div[1]/div[2]/div/div[3]/div[1]/div')
        close.click()
        search = driver.find_element("xpath",'/html/body/div[4]/div[2]/form/div[1]/div[1]/div[2]/div/div[2]/input')
        search.click()
        search.send_keys(f"{AmountInput} Dollar to {x}")
        search.send_keys(Keys.ENTER)
        try:
            Exchange = driver.find_element("xpath", f'/html/body/div[7]/div/div[11]/div/div[2]/div[2]/div/div/div[1]/div/div/div/div/div/div/div/div[3]/div[1]/div[1]/div[2]/span[1]').get_attribute('data-value')
        except:
            Exchange = driver.find_element("xpath", f'/html/body/div[7]/div/div[10]/div/div[2]/div[2]/div/div/div[1]/div/div/div/div/div/div/div/div[3]/div[1]/div[1]/div[2]/span[1]').get_attribute('data-value')
        Exchange = len(Exchange)

Where in this case {AmountInput} = "Ten" and AmountInputFinal = ["Pound", "Euro", "Canedian Dollar"]

My output however =

  • 12
  • 6
  • 18

why doesn't it work

I've tried to use normal xpath but that didnt work either. This is full XPath

Use WebDriverWait() and wait for visibility_of_element_located() and following xpath option

Exchange=WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//span[@data-value]"))).get_attribute("data-value")
print(Exchange)

You need to import below libarries.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM