简体   繁体   English

如何将 XPath 作为变量存储在 Python Selenium 中?

[英]How can I store an XPath as a variable in Python Selenium?

I want to be able to select text on a website, store it, and then turn that stored information into a variable.我希望能够在网站上将 select 文本存储起来,然后将存储的信息转换为变量。 More specifically as seen in the picutre below, my goal is for the selected name, in this case, John J. John, somehow be copied, turned into a variable, and then printed, all without emulating any key binds.更具体地说,如下图所示,我的目标是选定的名称,在这种情况下,John J. John,以某种方式被复制,变成一个变量,然后打印,所有这些都没有模拟任何键绑定。

HTML Inspect element photo HTML 检查元件照片

The code I have tried to use to get the information is this:我试图用来获取信息的代码是这样的:

selectedName = browser.find_element_by_xpath('//*[@id="sign_in_box"]/div/div[2]/div/div[1]/div').get_attribute("div")

print (selectedName)

The return I am getting is this:我得到的回报是这样的:

None

I know that the problem almost definetly lies somewhere in the path, but I can't figure it out.我知道问题几乎肯定出在路径的某个地方,但我无法弄清楚。

Assuming your xpath is correct, you should put .text instead of .get_attribute("div") since it will not return the text you want, but the div itself.假设您的 xpath 是正确的,您应该放置.text而不是.get_attribute("div")因为它不会返回您想要的文本,而是 div 本身。

How to get text with Selenium WebDriver in Python 如何在 Python 中使用 Selenium WebDriver 获取文本

Try尝试

selectedName = browser.find_element_by_xpath('//*[@id="sign_in_box"]/div/div[2]/div/div[1]/div').text

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

相关问题 如何使用相同的 xpath 单击 Python Selenium 中的多个项目? - How can I click multiple items in Python Selenium with the same xpath? 如何使用Selenium找到随机的Xpath? - How can I find the randomly Xpath using Selenium? 如何使用 Selenium 通过 XPath 选择兄弟姐妹的孩子? - How can I select the child of a sibling by XPath using Selenium? 如何将 php 查询存储在变量中? - How can i store a php query in a variable? 使用Python selenium在HTML代码中查找元素(带有变量xpath) - Find element (with variable xpath) in a HTML Code using Python selenium 在 python 中使用 xpath,我怎么能 select 只是元素的子部分? - Using xpath in python, how can I select only a subpart of elements? 如何使用Python删除XPath元素中的错误数据? - How can I remove bad data in an XPath element using Python? 无法使用xPath + PHP将HTML节点的externalHTML存储到变量中 - Can't store outerHTML of HTML node into variable using xPath + PHP 如何将 JavaScript 变量输出存储到 PHP 变量中? - How can I store JavaScript variable output into a PHP variable? 如何解决 selenium 中的此错误以进行循环? InvalidSelectorException:消息:无效选择器:无法找到具有 xpath 的元素 - How can I solve this error in selenium for a loop? InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM