简体   繁体   中英

Selenium + Python: Print text of an element located by CssSelector

I am new to Selenium and Python. I would like to navigate through a website, find an element and print it (or store it in a csv file).

Python version: 3.10; Selenium Webdriver: Firefox; IDE: PyCharm 2021.3.2 (CE); OS: Fedora 35 VM

So far I am able to navigate to the appropriate page where a table is generated. When I locate the element by CSS Selector and attempt to print it, the output does not print the text "$10.50" that I see on the screen. In fact, it does not print anything.

HTML code of the element I am trying to print:

<input id="b8-b36-Input_RemainAmtYr1" class="form-control OSFillParent" data-input="" disabled="" type="text" style="margin-top: 5px;" value="$10.50">
event

My relevant code:

RemainDue = driver.find_element(By.CSS_SELECTOR, '#b8-b36-Input_RemainAmtYr1')
print ('Remaining Due:', RemainDue.text)

I expect the output to be "$10.50", which is what I see on the screen and in the HTML. Instead I get the following:

Remaining Due:

There is nothing printed after "Remaining Due:" I thought the problem was that the "$10.50" was possibly being generated by some sort of javascript but I can see the text "$10.50" that I want to print in the HTML code above. What am I doing wrong?

To print the value of the value attribute ie $10.50 you can use either of the following locator strategies :

  • Using css_selector :

     print(driver.find_element_by_css_selector("input.form-control.OSFillParent[id$='Input_RemainAmtYr1']").get_attribute("value"))
  • Using xpath :

     print(driver.find_element_by_xpath("//input[@class='form-control OSFillParent' and contains(@id, 'Input_RemainAmtYr1')]").get_attribute("value"))

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following locator strategies :

  • Using CSS_SELECTOR :

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input.form-control.OSFillParent[id$='Input_RemainAmtYr1']"))).get_attribute("value"))
  • Using XPATH :

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@class='form-control OSFillParent' and contains(@id, 'Input_RemainAmtYr1')]"))).get_attribute("value"))
  • Note : You have to add the following imports:

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

You can find a relevant discussion in Python Selenium - get href value

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