[英]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>
理想情況下,我要選擇的是與以下字符串最匹配的選項
'Red, wooly, small, UK'
這將從下拉菜單中選擇第三項
可以用某種匹配器完成嗎? 如果是這樣,我如何從下拉菜單中選擇正確的元素?
謝謝
您是否嘗試過使用正則表達式? Python正則表達式以匹配第三行,甚至使用內置的.find()方法的python。 由於使用的是硒,因此可以找到所有的options元素,遍歷每個元素,檢查每個元素的文本,然后將其與字符串進行比較。
例如
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.