一、前置说明
selenium遇到下面这种元素:
<th id="demo id" class="value1 value2 value3 ">
1、虽然id一般不会有空格,但是前端错误的这种写法(如下图),会造成使用id定位不到元素,如:
find_element('id', 'demo id')
这种写法会直接报错。
2、class属性有空格,表示有多个属性,一般的解决办法就是使用其中一个属性,如:
find_element('class name', 'value1')
这种写法是可以定位到元素,但是往往测试人员在使用时,会将其错误的写成:
find_element('class name', 'value1 value2 value3')

二、解决方案
为了避免上述这种常见的错误,可以写一个方法封装一下,遇到这种错误时,将其转为xpath定位即可。
def _fix_find_elements_by_multiple_values_error(self, by, value) -> List[WebElement]:
"""
修复 `find_elements` 方法在使用 'id' 或 'class name' 定位时,
value为复合值(比如value='value1 value2')可能引发的 InvalidArgumentException。
"""
try:
return super().find_elements(by, value)
except InvalidArgumentException as original_e:
if by == 'class name':
by = 'class'
try:
return super().find_elements('xpath', f'//*[@{by}="{value}"]')
except:
raise original_e
三、Demo验证
欢迎技术交流:






![[Linux] Bash脚本多函数应该如何执行?使用eval提高脚本编写效率!](https://img-blog.csdnimg.cn/img_convert/19e4ae3377458e3f2986ef0e00f5e1c6.jpeg)










![[原创][6]探究C#多线程开发细节-“ConcurrentDictionary<T,T>解决多线程的无顺序性的问题“](https://img-blog.csdnimg.cn/direct/6c82d2c3cf914c4c81003f29b93ac9b8.gif)


