【问题标题】:python3/selenium/automation - find ID that contains a given stringpython3/selenium/automation - 查找包含给定字符串的 ID
【发布时间】:2017-09-09 23:51:48
【问题描述】:

所以基本上我在做网页抓取/网站自动化,

这是我正在尝试做的一个简单示例:

我正在处理一个包含表单的动态页面,我想在这个表单中插入数据。

当然,这个动态页面会根据我在此页面上发生之前插入的内容而变化。这是我尝试在其中插入数据的 5 个不同页面的输入字段 ID 的示例。因此它是自动生成的,并且是唯一的:

  1. Listing.Item[国际象棋大小]
  2. Listing.Item[鞋尺码]
  3. Listing.Item[尺码裤子]
  4. Listing.Item[尺寸]
  5. Listing.Item[鞋尺码]

同样的模式是这里的字符串“Size”。

我需要在这个字段中插入数据,否则我无法在表单上前进。所以这就是我尝试过的:

driver.find_element_by_id('Listing.Item[' + any(str) + 'Size' + any(str) + ']')

但它不起作用。也许我错误地使用了函数'any()'。

如何在我遇到的每个页面中自动找到这个唯一输入,其 ID 中始终包含字符串“Size”?

XPath 和 CSS 选择器还包含另一个词(例如:Chess、Shoe 和 Trouser),因此我无法使用它们

感谢帮助

编辑:

这是整个相应的 HTML:

 <input type="text" id="Listing.Item[Shoe Size]"
 name="_st_Shoe Size" size="21" maxlength="50"
 aria-required="true" value="">

=> name 和 id 的值每次都会改变

【问题讨论】:

    标签: python selenium automation beautifulsoup


    【解决方案1】:

    您可能想尝试的是find_elements_by_css_selector。这个函数接受(顾名思义)css选择器来返回元素。

    CSS 选择器允许您搜索包含特定值的 id。

    例如,如果您要搜索所有 id 包含单词“Size”的输入标签,您可以使用:

    css_selector = 'input[id*=Size]'
    driver.find_elements_by_css_selector(css_selector)
    

    *= 表示“包含”。

    以下是一些可能对您有帮助的资源:

    Selenium CSS Selectors

    Another question similar to this

    Nice compilation of CSS selectors

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2013-05-13
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多