Использование BeautifulSoup для поиска HTML-тега, содержащего определенный текст
-
21-08-2019 - |
Вопрос
Я пытаюсь получить элементы в HTML-документе, содержащие следующий образец текста:#\S{11}
<h2> this is cool #12345678901 </h2>
Итак, предыдущее будет соответствовать использованию:
soup('h2',text=re.compile(r' #\S{11}'))
И результаты будут примерно такими:
[u'blahblah #223409823523', u'thisisinteresting #293845023984']
Я могу получить весь соответствующий текст (см. строку выше).Но я хочу, чтобы родительский элемент текста совпадал, чтобы я мог использовать его в качестве отправной точки для обхода дерева документа.В этом случае я бы хотел, чтобы возвращались все элементы h2, а не совпадение текста.
Идеи?
Решение
from BeautifulSoup import BeautifulSoup
import re
html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h1>foo #126666678901</h1>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""
soup = BeautifulSoup(html_text)
for elem in soup(text=re.compile(r' #\S{11}')):
print elem.parent
Распечатки:
<h2>this is cool #12345678901</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
Другие советы
Поисковые операции BeautifulSoup предоставляют [список] BeautifulSoup.NavigableString
объекты, когда text=
используется в качестве критерия, а не BeautifulSoup.Tag
в других случаях.Проверьте объект __dict__
чтобы увидеть доступные вам атрибуты.Из этих атрибутов parent
имеет преимущество перед previous
из-за изменения в BS4.
from BeautifulSoup import BeautifulSoup
from pprint import pprint
import re
html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""
soup = BeautifulSoup(html_text)
# Even though the OP was not looking for 'cool', it's more understandable to work with item zero.
pattern = re.compile(r'cool')
pprint(soup.find(text=pattern).__dict__)
#>> {'next': u'\n',
#>> 'nextSibling': None,
#>> 'parent': <h2>this is cool #12345678901</h2>,
#>> 'previous': <h2>this is cool #12345678901</h2>,
#>> 'previousSibling': None}
print soup.find('h2')
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern)
#>> this is cool #12345678901
print soup.find('h2', text=pattern).parent
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern) == soup.find('h2')
#>> False
print soup.find('h2', text=pattern) == soup.find('h2').text
#>> True
print soup.find('h2', text=pattern).parent == soup.find('h2')
#>> True
С bs4 (Beautiful Soup 4) попытка ОП работает точно так, как ожидалось:
from bs4 import BeautifulSoup
soup = BeautifulSoup("<h2> this is cool #12345678901 </h2>")
soup('h2',text=re.compile(r' #\S{11}'))
возвращает [<h2> this is cool #12345678901 </h2>]
.