简体   繁体   English

如何为使用Javascript工具提示定义的Web元素查找Xpath?

[英]How to find Xpath for a web element defined using a Javascript tooltip?

When the Tweets figure on someone's Twitter page is in the thousands, Twitter rounds it to eg 12.4K. 当某人的Twitter页面上的Tweets数字成千上万时,Twitter会将其四舍五入为12.4K。 When you move the mouse over this element, a tooltip tells you the true number eg 12,412. 将鼠标移到该元素上时,工具提示会告诉您真实的数字,例如12,412。

I'm looking to get this actual figure using Selenium WebDriver (probably with its find_element_by_xpath function). 我正在寻找使用Selenium WebDriver(可能带有它的find_element_by_xpath函数)的实际数字。

If we take this Twitter page as an example, and inspect the element in Firebug: 如果我们以 Twitter页面为例,并检查Firebug中的元素:

在此处输入图片说明

Note that for Firebug to display this HTML, I needed to first click on, in the Style tab of the sidebar: 请注意,要使Firebug显示此HTML,我需要先在侧边栏的“样式”选项卡中单击:

在此处输入图片说明

And the XPath for the anchor is: 锚点的XPath是:

/html/body/div[2]/div[2]/div/div[1]/div/div[2]/div/div/div[2]/div/div/ul/li[1]/a

From there, I would think I could simply tag on /@data-original-title to this Xpath, and any program that tries to fetch this would succeed. 从那里,我想我可以简单地在此Xpath的/@data-original-title上标记,任何尝试获取此名称的程序都将成功。 Yet both Webdriver's find_element_by_xpath nor Google Sheet's importXml() fail to retreive anything. 但是,Webdriver的find_element_by_xpath或Google Sheet的importXml()无法检索任何内容。

I know very little about Javascript or CSS, but I imagine that the fact that I needed to click on the "Inherited From" would suggest that one or both are involved in my challenge. 我对Javascript或CSS知之甚少,但我想我需要单击“继承自”这一事实会暗示一个或两个都参与了我的挑战。 If so, how so? 如果是这样,怎么办? Can such an XPath query ever succeed in a case like this? 这样的XPath查询在这种情况下能否成功? If not, how can the exact Tweets number be gotten? 如果没有,如何获得确切的Tweets号?

@ Webdriver Experts: Is there a way of mimicking such a mouseover in order to retrieve this value? @ Webdriver专家:是否有一种模仿这种鼠标悬停的方法来检索此值?

If you want to hover over and then get the count of tweets that would be a lot more unnecessary works. 如果要悬停然后获取推文计数,那将是更多不必要的工作。 As a workaround I would simply use the following JavaScript and get the count. 解决方法是,仅使用以下JavaScript并计数。

str = "return $(\"[href*='TheEllenShow/following']\").attr('data-original-title');"
count = driver.execute_script(str)

On the other hand, the actual count of tweets is saved in an attribute. 另一方面,推文的实际计数保存在属性中。 In that case you should be able to find the element and get the attribute on the element to get the count as shown bellow: 在这种情况下,您应该能够找到该元素并获取该元素上的属性以获取计数,如下所示:

element = driver.find_element(By.CSS_SELECTOR, "[href*='TheEllenShow/following']")
attr = element.get_attribute("data-original-title")

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

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