我可以使用xml.etree.ElementTree中的element.findall()来查找单个属性中包含多个值的元素吗?
我可以用它来查找class =“day”的所有div元素:
from xml.etree.ElementTree import ElementTree
calendar = ElementTree()
calendar.parse("calendar-week.xml")
calendar.findall('.//div[@class="day"]')
或者这样找到class =“first day”的所有div元素:
calendar.findall('.//div[@class="first day"]')
但是有没有办法在班上找到所有带有“day”的div元素?我找不到任何关于如何做到这一点的文档。有没有办法在这里使用正则表达式?
<body>
<div class="calendar-week">
<div class="first day" id="su">Sunday</div>
<div class="day" id="mo">Monday</div>
<div class="day" id="tu">Tuesday</div>
<div class="day" id="we">Wednesday</div>
<div class="day" id="th">Thursday</div>
<div class="day" id="fr">Friday</div>
<div class="last day" id="sa">Saturday</div>
<div class="clear-float"></div>
</div><!-- /calendar-week -->
</body>
答案 0 :(得分:1)
这个xpath就是你通常会这样做的方式:
'//div[contains(concat(" ", @class, " "), " day ")]'
答案 1 :(得分:1)
此代码基于@stranac
的答案中提供的xpath术语from lxml import etree as ET
calendar = ET.ElementTree()
calendar.parse("calendar-week.xml")
elem_list = calendar.xpath('//div[contains(concat(" ", @class, " "), " day ")]')