【问题标题】:How do I get attribute for non tagged text inside div如何在 div 中获取非标记文本的属性
【发布时间】:2020-07-23 20:09:09
【问题描述】:

我目前正在使用 python(和 selenium)编写脚本,当我尝试在此 div 中获取文本(III. AIR COMBAT)时遇到一些问题:

<div class="vs901-4">
<i id="copyarticle" style="cursor:pointer; color:white;margin-right:10px;" class="fa fa-copy"></i>
<span id="copiednotif" class="badge badge-pills badge-success" style="text-weight:300;cursor:pointer; margin-left: 5px;margin-right:5px;"></span>
<span id="profileid" class="hidden"> website link</span>
                             III. AIR COMBAT</div>

所以基本上我尝试了通常的完整 xpath 方式:

self.driver.find_element_by_xpath("/html/body/div[2]/div/div[2]/div[2]/div/div/div/div/div/div[1]/div[4]/text()").get_attribute("innerHTML") 

这基本上是我用于其他我需要的文本的内容(其他文本不在未标记的 div 中)并且它们都有效,但是这个给了我这个错误:

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

感谢您的帮助。

【问题讨论】:

  • 请包含 xpath_code。因为那是你的错误发生的地方,你至少应该包括变量的值是什么。
  • 添加了 xpath 代码
  • 能否也提供网址?
  • 你试过//div[@class='vs901-4']/text()[last()] xpath吗?
  • 是的@supputuri,//div[@class='vs901-4']/text()[last()] 给了我同样的错误

标签: javascript python html selenium selenium-webdriver


【解决方案1】:

这是您可以使用 javascript 直接返回文本的代码行。

def get_text_exclude_children(element):
    return driver.execute_script(
        """
        var parent = arguments[0];
        var child = parent.firstChild;
        var textValue = "";
        while(child) {
            if (child.nodeType === Node.TEXT_NODE)
                textValue += child.textContent;
                child = child.nextSibling;
        }
        return textValue;""",
        element).strip() 

现在你可以使用如下所示的方法了。

element = driver.find_element_by_xpath("//div[@class='vs901-4']")
elementOnlyText = get_text_exclude_children(element)
print(elementOnlyText)
```

【讨论】:

    【解决方案2】:

    错误似乎在 xpath 的 /text() 中,您已经在其中获取文本而不是元素,然后获取 innerHTML。尝试以下方法:

    self.driver.find_element_by_xpath("/html/body/div[2]/div/div[2]/div[2]/div/div/div/div/div/div[1]/div[4]").get_attribute("innerHTML") 
    

    self.driver.find_element_by_xpath("/html/body/div[2]/div/div[2]/div[2]/div/div/div/div/div/div[1]/div[4]/text()")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多