在解析“名字"时遇到麻烦.从网页
问题描述:
如何在脚本中从目标页面获取名字".我已经尝试过以下操作,但是会引发以下错误:
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."
但是,我在其中使用"First Name"的元素:
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()
答
Selenium
不支持此语法.您的XPath
表达式应仅返回WebElement
,而不返回属性值或文本.尝试改用以下代码:
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)