首页 > 解决方案 > 从 python 中的 webElement 中查找 xpath

问题描述

我正在尝试使用 python 抓取一些页面,使用 Selenium,但我有一个问题。由于页面结构不同,我正在寻找的元素具有不同的 xpath,但它们都位于页面的同一部分,具有相同的类名。所以我想知道是否有可能,一旦我得到 webElement,知道它的类名,以及我感兴趣的页面部分,找到这部分页面的 XPath。

我这样做是为了找到页面的一部分:

interestedPart = driver.find_element_by_class_name("_45kb")

但是在那之后我不知道如何找到“interestedPart”完整的XPath,你能帮我吗?

完整 XPath 的示例:

/html/body/div[1]/div/div[4...

标签: pythonseleniumweb-scraping

解决方案


是的,有可能

element.get_attribute('class')

xpath = "//div[@class='"+element.get_attribute('class')+"']"

对于您的示例 Webelement,称为 InterestPart:

xpath = "//div[@class='"+interestedPart.get_attribute('class')+"']"


推荐阅读