【问题标题】:How to find the id of children in selenium如何在 selenium 中找到孩子的 id
【发布时间】:2021-05-06 03:14:12
【问题描述】:

我是 Web 开发的新手,我正在 Python 中试验 Selenium。

鉴于我只知道 class="entry-content" 作为其父级,我想在下面找到孩子的 id。

示例 html:

<div class="entry-content">
  <div id="pl-154">
    ...
  </div>
</div>

示例输出:

pl-154

先谢谢你!

更新:感谢大家的 cmets!但是,当我在我正在使用的网站上尝试代码时,它不起作用,我不知道为什么。

【问题讨论】:

标签: python python-3.x selenium selenium-webdriver web-scraping


【解决方案1】:

由于您正在寻找孩子,您可以使用 CSS SELECTOR 或 XPATH。我会推荐 cssselector。

CSS 选择器: 如果您在&lt;div class="entry-content"&gt; 中有多个 id 的 div

div[class='entry-content']>div

上面的css选择器会给你&lt;div class="entry-content"&gt;里面的所有div

你可以试试div[class='entry-content']+div

如果您正在寻找 xpath,它会是这样的:

//div[@class='entry-content']/div or //div[@class='entry-content']/child::div

无论你使用什么,确保使用 get_attribute(attribute name) 来获取属性值。

div_id_value = driver.find_element_by_xpath("//div[@class='entry-content']/div").get_attribute('id')
print(div_id_value)
   

CSS SELECTOR REFRENCE

XPATH REFRENCE

【讨论】:

  • @chocolatte :以文本格式共享该 html 以及错误堆栈跟踪。
  • @chocolatte : 其实你可以试试div_id_value = driver.find_element_by_xpath("//div[@class='entry-content']/div[@class='panel-layout']").get_attribute('id') print(div_id_value)
  • 如果你不介意我问,为什么div_id_value = driver.find_element_by_xpath("//div[@class='entry-content']/div").get_attribute('id') 最初不工作?没有错误,但 div_id_value 为空
  • @chocolatte :这可能是因为//div[@class='entry-content']/div 可能在 DOM 中有多个条目。建议转到开发工具并检查提到的 xpath 并查看存在多少条目。
  • @chocolatte:是的,正确。现在你有 3 个孩子,所以你必须区分选择哪个,如果没有声明,只有第一个孩子应该得到偏好
【解决方案2】:

您可以将./child::* 表达式与xpath 一起使用

element = driver.find_element_by_xpath("//div[@class='entry-content']")
child = element.find_element_by_xpath("./child::*")
idVal = child.get_attribute('id'))

您的id 值应存储在idVal 变量中
我不确定您使用的是哪个版本的 Python,但这应该适用于 Python3

【讨论】:

  • 谢谢!第一行有效,但在第二行中,孩子是空的。只有一个孩子才有效吗?
【解决方案3】:

以下代码将为您提供子对象的 ID

id_Value = driver.find_element_by_xpath("//div[@class='entry-content']/div").get_attribute('id'))

【讨论】:

  • 这里的字符串是什么?
  • get_attribute 返回一个字符串,我们在字符串“id_Value”@cruisepandey 中捕获它
  • @RajanDomala:你为什么要在 Python 中这样做?
  • @cruisepandey 典型的 Java 人回答,抱歉,更新了答案
猜你喜欢
  • 2010-11-02
  • 2021-06-29
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多