Python 代码:使用欧氏距离匹配输入元素与文本元素
{"title": "Python 确认输入元素和文本元素的对应关系", "description": "这段代码用于确认输入元素和文本元素之间的对应关系。它通过计算输入元素和文本元素的坐标之间的正视距离来实现。", "keywords": "Python, 代码, 输入元素, 文本元素, 对应关系, 正视距离, 坐标", "content": "有如下两段代码: 1:inputs_attributes = {} inputs_attributes_ele = {} for element in inputs: if element.is_displayed() and element.get_attribute("type") != "hidden": key = element.get_attribute("value") location = element.location if key in inputs_attributes: if location not in [t["coordinate"] for t in inputs_attributes[key]]: inputs_attributes[key].append({"id": element.get_attribute("id"), "coordinate": location, "data-placeholder": element.get_attribute( "data-placeholder"), "type": element.get_attribute("type"), "accessible_name": element.get_attribute("accessible_name"), "class": element.get_attribute("class") }) 2:text_elements = driver.find_elements(By.XPATH, '//*[text()]') text_attributes = {} text_attributes_ele = {} for element in text_elements: try: text = element.text if text != '' and ' ' not in text: location = element.location if location['x'] == 0: continue tag_name = element.tag_name if text in text_attributes: if location not in [t["coordinate"] for t in text_attributes[text]]: text_attributes[text].append({"coordinate": location, "tag_name": tag_name}) 在现在我新建了一个函数def Fields_Input(inputs_attributes,text_attributes),请帮助我补充,功能是将inputs_attributes和text_attributes里面"coordinate"对应的location正视距离最近的进行配对,保存在 dict 字典里,key 是inputs_attributes的 key,value是text_attributes的 key内容:以下是补充的函数代码:
import math
def Fields_Input(inputs_attributes, text_attributes):
dict = {}
for key in inputs_attributes:
min_distance = math.inf
closest_text = None
for text_key in text_attributes:
for input_attr in inputs_attributes[key]:
for text_attr in text_attributes[text_key]:
input_coordinate = input_attr["coordinate"]
text_coordinate = text_attr["coordinate"]
distance = math.sqrt((input_coordinate["x"] - text_coordinate["x"]) ** 2 +
(input_coordinate["y"] - text_coordinate["y"]) ** 2)
if distance < min_distance:
min_distance = distance
closest_text = text_key
dict[key] = closest_text
return dict
这个函数会通过inputs_attributes中的每个key,然后对应每个key找到与其"coordinate"对应的location正视距离最近的text_attributes的key,并将它们保存在dict字典中。最后,函数会返回这个字典。
原文地址: https://www.cveoy.top/t/topic/qdyg 著作权归作者所有。请勿转载和采集!