【问题标题】:Trouble parsing the "First name" from a webpage无法从网页解析“名字”
【发布时间】:2023-04-01 08:28:02
【问题描述】:

如何从脚本中的目标页面获取“名字”。我已经尝试如下,但它会引发以下错误:

"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()

【问题讨论】:

    标签: python selenium xpath selenium-webdriver web-scraping


    【解决方案1】:

    您不能在 Selenium 中使用 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")
    

    【讨论】:

    • get_attribute() 方法不适用于webdriver 实例。你的意思是name_attribute = name_element.get_attribute("value")
    • 感谢 alecxe 先生,感谢您提供强大的解决方案。我投了赞成票。
    【解决方案2】:

    Selenium 不支持这种语法。您的XPath 表达式应该只返回WebElement,而不是属性值或文本。尝试使用以下代码:

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

    【讨论】:

    • 感谢 Andersson 先生的有效解决方案。
    猜你喜欢
    • 2012-08-20
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多