【问题标题】:How to get tag name in Selenium Python?如何在 Selenium Python 中获取标签名称?
【发布时间】:2020-10-12 20:07:34
【问题描述】:

有什么方法可以获取 selenium web 元素的标签名称吗??

我发现,在 selenium for java 中有.getTagName()这里:https://www.tutorialspoint.com/how-do-i-get-a-parent-html-tag-with-selenium-webdriver-using-java

编辑

示例:在此 HTML 中,如果我通过 class='some_class_name' 进行迭代,我如何获得 tag_name(h2pulli

<div class='some_class_name'>
    <h2>Some Random Heading 1</h2>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>

    <h2>Some Random Heading 2</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    <p>Random list are:</p>
    <ul>
        <li>Lorem</li>
        <li>Ipsum</li>
        <li>Dolor</li>
    </ul>
</div>

Python 代码可能如下所示..

content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
    print(c.getTagName())      # something like this to get the tag of inner content..

【问题讨论】:

  • 当然可以:driver.find_elements_by_tag_name('li') Makre 确保使用elements而不是element,以便获取所有li 标签
  • 感谢您的评论,但我不想那样做。我已经编辑了问题。
  • 嘿@AnupaM,如果你举一个例子来说明你希望找到的例子,它可能会有所帮助。我没有按照你的意思 tag Name 是内部 HTML 吗?
  • @DanielButler 我已经进行了编辑,希望我现在很清楚,并且会得到任何解决方案。
  • 啊,问题似乎在于获取嵌套在选择器找到的元素的标签名称,因此在此示例中为lis。准确吗?

标签: python selenium


【解决方案1】:

Python 你有tag_name 来获取标签名称。

content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
     print(c.tag_name)

【讨论】:

    【解决方案2】:

    我使用两种方式:for 的情况下我不知道li 的位置,但是当我确切知道它在哪里并且我需要选择它时,我可以这样使用它:

    tEx = driver.find_elements_by_tag_name('div[class='some_class_name'] ul li')
    

    在示例中,它将把 3 个lis 的元素带到ul 的下方,因此要选择其中一个,取决于您要查找的一个,它看起来像这样:

    tEx = driver.find_elements_by_tag_name('div[class='some_class_name'] ul li')[0]
    

    tEx = driver.find_elements_by_tag_name('div[class='some_class_name'] ul li')[1]
    

    tEx = driver.find_elements_by_tag_name('div[class='some_class_name'] ul li')[2]
    

    或简化:

    tEx = driver.find_elements_by_tag_name('div[class='some_class_name'] ul li')
    tEx[n].click()
    

    注意:将“n”替换为您要选择的li对应的数字。

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 2013-05-24
      • 2022-11-11
      • 2014-07-12
      • 1970-01-01
      • 2018-12-06
      • 2011-11-18
      • 2021-07-03
      相关资源
      最近更新 更多