Python 硒和模糊匹配

Python selenium and fuzzy matching

我正在使用 Selenium 填充一些下拉菜单。这些下拉菜单相当动态。

不过我所拥有的是下拉列表中可能存在的值,例如:

<select>
    <option>Red, wooly, jumper, large, UK</option>
    <option>Blue, wooly, jumper, small, USA</option> 
    <option>Red, wooly, scarf, small, UK</option>
</select>

理想情况下,我想要做的是 select 与以下字符串最匹配的选项

'Red, wooly, small, UK'

这将是 select 下拉列表中的第 3 项

这可以用某种匹配器来完成吗?如果是这样,我如何 select 从下拉列表中选择正确的元素?

谢谢

您尝试过使用正则表达式吗?? Python 正则表达式来匹配第三行,甚至使用 pythons 内置的 .find() 方法。由于您使用的是 selenium,因此您可以找到所有选项元素,遍历每个元素,检查每个元素的文本,并将其与您的字符串进行比较。

例如

elem = browser.find_elements_by_tag_name("option") 
for ele in elem:
  if ele.get_attribute("innerHTML").find('Red') > -1 and ele.get_attribute("innerHTML").find('wolly') > -1 and ele.get_attribute("innerHTML").find('small') > -1 and ele.get_attribute("innerHTML").find('small') > -1:
    #TODO

但是这有点长,所以我会使用正则表达式,例如:

import re
elem = browser.find_elements_by_tag_name("option") 
for ele in elem:
  m = re.search(r'(Red,.+wooly,.+small,.+UK)', ele.get_attribute("innerHTML"))
  if m:
    print m.group(1)

如果.get_attribute("innerHTML")没有得到内部文本尝试.text()

您可以从选项中获取文本,然后比较您的文本,如下所示:

elms = driver.find_elements_by_css_selector("select > option")
ops = []
for el in elms:
    ops.append(el.text)

s = 'Red, wooly, small, UK'.split(", ")

weight = []

for op in ops:
    n_occurance = 0
    for text in s:
        if text in op:
            n_occurance += 1

    weight.append(n_occurance)

most_like = weight.index(max(weight)

elems[most_like].click()