从网页解析“名字”时出错
问题描述:
如何从脚本中的目标页面获取“名字”?我试着像下面,但它引发以下错误:从网页解析“名字”时出错
"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."
然而,在其中“名”我以后元素:
<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>
的剧本我已经试过到目前为止:
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
,但不返回属性值或文本。尝试使用下面的代码来代替:
name = driver.find_element_by_xpath('//div[@class="div_input_place"]/input[@id="txt_name"]').get_attribute('value')
print(name)
答
您无法定位与XPath的属性中硒 - 表达式必须始终符合实际的元素:
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)
请注意,我也想切换一个更简明易读的CSS选择:
driver.find_element_by_css_selector('.div_input_place input#txt_name')
或者说,即使有“按ID查找”,如果你的ID是唯一的去:
driver.find_element_by_id("txt_name")
谢谢先生安德森,为您的有效解决方案。 – SIM