【问题标题】:Is there a way to find an element by attributes in Python Selenium?有没有办法在 Python Selenium 中按属性查找元素?
【发布时间】:2015-04-10 04:31:37
【问题描述】:

我得到了一个像这样的 html sn-p:

<input type="text" node-type="searchInput" autocomplete="off" value="" class="W_input" name="14235541231062">

这个元素在 html 中唯一的唯一标识是属性node-type="searchInput",所以我想使用 Python selenium 的 some method 来定位它,如下所示:

search_elem = driver.find_element_by_xxx("node-type","searchInput") # maybe?

我已经检查了 selenium(python) document for locating elems,但不知道如何通过 node-type attr 找到这个元素。有没有明确的方法可以在 python selenium 中找到这个元素?

【问题讨论】:

标签: python selenium


【解决方案1】:

尽管这个问题很老,但我相信它仍然非常相关。 您也许可以使用简单的 css 选择器,语法是类似于 jquery 的标准 javascript 或本机浏览器支持。

driver.find_element_by_css_selector('span.className[attrName="attrValue"]')

示例: driver.find_element_by_css_selector('span.blueColor[shape="circle"]')

【讨论】:

  • 不属于类的标签怎么办?
【解决方案2】:

您可以使用以下方法:

save_items = []

for item in driver.find_elements_by_tag_name("input"):
    # Get class
    item_class = item.get_attribute("class")

    # Get name:
    item_name = item.get_attribute("name")

    # And so on...


    # Check for a match
    if item_class == "W_input" and item_name == "14235541231062":
        # Do your operation (or add to a list)
        save_items.append(item)

【讨论】:

  • 这不是很慢吗?
  • 在规模上,可能是@EkremDİNÇEL
【解决方案3】:

你可以通过xpath获取并查看node-type属性值:

driver.find_element_by_xpath('//input[@node-type="searchInput"]')

【讨论】:

  • 属性的 CSS 选择器表示法是:tag_name[attribute_name=attribute_value]。比 XPath 更简单、更快
  • AttributeError: 'WebDriver' object has no attribute 'tag_name' 如何访问 tag_name?
猜你喜欢
  • 2018-09-01
  • 2016-06-19
  • 2013-07-03
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多