现在我正在使用以下代码:
containers = html_soup.find_all('div', class_ = 'a')
然后我使用if语句如下:
if containers[i].p.text == 'text':
但这需要花费很多时间。
我的问题是我可以在第一行代码中进行修改以使其更快。我想找到包含某个文本的段落的兄弟姐妹。 基本上这段是div的孩子
答案 0 :(得分:0)
将函数传递给find_all
,检查text,tag和parent标记是否匹配。
def find_siblings_for_element_with_text(html_soup, text, tag='p', parent_tag='div'):
result_set = html_soup.find_all(
lambda el: (
el.text == text
and el.name.lower() == tag
and el.parent.name == parent_tag)
)
return [
list(el.previous_siblings) + list(el.next_siblings)
for el in result_set
]
find_siblings_for_element_with_text(html_soup, 'text')