简体   繁体   English

无法在 selenium 和 Z23EEEB4347BDD26BFC6B7EE9A3B75 中使用 xpath 的元素 select

[英]unable to select an element using xpath in selenium and python

I've been trying to select an element by xpath and display it but I get an error everytime I try to run the code.我一直在尝试 xpath 的元素 select 并显示它,但每次尝试运行代码时都会出错。 I got the xpath by doing inspect element and copying full xpath yet it gives me the error.我通过检查元素并复制完整的 xpath 得到了 xpath,但它给了我错误。 It's a dynamic form too, so I can't choose the direct text and I would probably need to use an address to locate that element as it changes everytime but I've not been able to select that certain element.它也是一种动态形式,因此我无法选择直接文本,并且我可能需要使用地址来定位该元素,因为它每次都会更改,但我无法 select 那个特定元素。 how do I choose the element?如何选择元素?

this is how I tried to choose the element这就是我尝试选择元素的方式

name_from_doc=browser.find_element_by_xpath('/html/body/form/div[3]/div[3]/div/div[4]/div/div[2]/div[4]/div[2]/text()[1]')
print(name_from_doc)

the error that I get is我得到的错误是

InvalidSelectorException: Message: invalid selector: The result of the xpath expression "/html/body/form/div[3]/div[3]/div/div[4]/div/div[2]/div[4]/div[2]/text()[1]" is: [object Text]. It should be an element.

I want to store the name of the person separately and address separately in two different variables我想将人名分别存储在两个不同的变量中

在此处输入图像描述

As the Billing Address text would always be there, so can reach there by using its text in the xpath and then find its exact value by using following in the xpath.由于Billing Address文本将始终存在,因此可以通过使用 xpath 中的文本到达那里,然后通过使用 xpath 中的following找到其确切值。
You can do it like:你可以这样做:

name_from_doc = browser.find_element_by_xpath("//div[contains(text(),'Billing Address')]//following::div[1]//br[2]")
print(name_from_doc.text)

To get the value NAPERVILLE IL Use follwoing xpath to get the element and then use splitlines() and last index value.要获取值NAPERVILLE IL使用以下 xpath 获取元素,然后使用splitlines()和最后一个索引值。

name_from_doc=browser.find_element_by_xpath('//div[contains(.,"Billing Address")]/following::div[1]').text
print(name_from_doc.splitlines()[-1])

Update :更新

name_from_doc=browser.find_element_by_xpath('//div[contains(.,"Billing Address")]/following::div[1]').text
print(name_from_doc.splitlines()[0])
print(name_from_doc.splitlines()[1])
print(name_from_doc.splitlines()[-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM