Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble parsing the "First name" from a webpage

How can I get the "First Name" from the target page in my script. I've tried like below but it throws the following error:

"selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//div[@class="div_input_place"]/input[@id="txt_name"]/@value" is: [object Attr]. It should be an element."

However, the element within which the "First Name" I'm after:

<div class="div_input_place">
                                                <input name="txt_name" type="text" value="CLINTO KUNJACHAN" maxlength="20" id="txt_name" disabled="disabled" tabindex="2" class="aspNetDisabled textboxDefault_de_active_student">
                                            </div>

The script I've tried with so far:

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://www.icaionlineregistration.org/StudentRegistrationForCaNo.aspx")
driver.find_element_by_id('txtRegistNo').send_keys('SRO0394294')
driver.find_element_by_id('btnProceed').click()
time.sleep(5)
name = driver.find_element_by_xpath('//div[@class="div_input_place"]/input[@id="txt_name"]/@value')
print(name.text)
driver.quit()
like image 230
SIM Avatar asked Nov 20 '25 05:11

SIM


2 Answers

Selenium doesn't support this syntax. Your XPath expression should return WebElement only, but not attribute value or text. Try to use below code instead:

name = driver.find_element_by_xpath('//div[@class="div_input_place"]/input[@id="txt_name"]').get_attribute('value')
print(name)
like image 53
Andersson Avatar answered Nov 22 '25 19:11

Andersson


You cannot target the attributes with XPaths in Selenium - the expressions have to always match the actual elements:

name_element = driver.find_element_by_xpath('//div[@class="div_input_place"]/input[@id="txt_name"]')
name_attribute = name_element.get_attribute("value")
print(name_attribute)

Note that I'd also switch to a more concise and readable CSS selector:

driver.find_element_by_css_selector('.div_input_place input#txt_name')

Or, even go with "find by id" if your id is unique:

driver.find_element_by_id("txt_name")
like image 26
alecxe Avatar answered Nov 22 '25 18:11

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!