Первый метод: у вас есть строка, поэтому вы можете использовать функции строки для фильтрации результатов - ie.
if text.strip().startswith('g:=Graph') :
Пример:
data = '''<font color="DarkBLUE">
g:=Graph<5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }>;</font>
<font color="DarkBLUE">h:=Other<...>;</font>'''
import lxml.html as lh
tree = lh.fromstring(data)
rate = tree.xpath("//font[@color='DarkBLUE']")
for item in rate:
text = item.text_content()
text = text.strip()
if text.startswith('g:=Graph'):
print(' OK:', text)
else:
print('NOT:', text)
Второй метод: Вы можете использовать xpath
для фильтрации
tree.xpath("//font[@color='DarkBLUE' and contains(text(), 'g:=Graph')]")
или
tree.xpath("//font[@color='DarkBLUE'][contains(text(), 'g:=Graph')]")
Пример:
data = '''<font color="DarkBLUE">
g:=Graph<5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }>;</font>
<font color="DarkBLUE">h:=Other<...>;</font>'''
import lxml.html as lh
tree = lh.fromstring(data)
rate = tree.xpath("//font[@color='DarkBLUE' and contains(text(), 'g:=Graph')]")
for item in rate:
text = item.text_content()
text = text.strip()
print(text)
В конечном итоге с starts-with()
, но текст в данных находится в новой строке, поэтому текст в xpath должен \n
в начале
tree.xpath("//font[@color='DarkBLUE' and starts-with(text(), '\ng:=Graph')]")
BTW: xpath cheatsheet