filter get_attribute用于项目结果



当前,我正在使用get_attribute在加载后立即在页面上获取所有数据ID实例。但是我想弄清楚的是如何过滤一些这些结果。特别是那些具有某些值的数据类型属性值的值。无论如何我可以做到吗?

ids = [item.get_attribute('data-id')for webdriverwait(驱动程序,30).until(ec.presence_of_all_elements_located)P>

您可以在列表中添加一个条件:

if item.get_attribute('data-type') == "yourValue"

然后看起来像这样:

els = WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[data-id]")))
ids = [item.get_attribute('data-id') 
       for item in els if item.get_attribute('data-type') == "yourValue"]

编辑:
item.get_attribute('data-type')的值不是"刀",而是"刀"。(末端的空间)

解决方案1:使用strip()删除空格:

if item.get_attribute('data-type').strip() == "Knife"

解决方案2:在

中使用
 if "Knife" in item.get_attribute('data-type')

解决方案3:添加一个空间!

if item.get_attribute('data-type') == "Knife "

edit2:如果要匹配多个值,请使用:

accepted_type = ("Knife", "Knife2",...)
if item.get_attribute('data-type').strip() in accepted_type

最新更新