Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 使用beautifulsoup基于2个连续标记选择标记_Python 2.7_Beautifulsoup - Fatal编程技术网

Python 2.7 使用beautifulsoup基于2个连续标记选择标记

Python 2.7 使用beautifulsoup基于2个连续标记选择标记,python-2.7,beautifulsoup,Python 2.7,Beautifulsoup,我一直在尝试使用find_all()方法选择标记h1,将下一个元素作为p,但得到的是空列表。这是我的密码 def has_h1_followedby_p(tag): return tag.name == 'h1' and tag.next_siblings.name == 'p' soup = BeautifulSoup(open(filepath), 'html.parser') h1_tags = soup.find_all(has_h1_followedby_p) 我想知道这个

我一直在尝试使用find_all()方法选择标记h1,将下一个元素作为p,但得到的是空列表。这是我的密码

def has_h1_followedby_p(tag):
    return tag.name == 'h1' and tag.next_siblings.name == 'p'

soup = BeautifulSoup(open(filepath), 'html.parser')
h1_tags = soup.find_all(has_h1_followedby_p)
我想知道这个条件到底出了什么问题,因为它看起来很简单。我将非常感谢您的建议。

是一个发电机,可以匹配所有下一个兄弟姐妹,而您需要一个:

tag.name == 'h1' and tag.next_sibling and tag.next_sibling.name == "p"
请注意,我们还应用了
标记。next_sibling
真实性检查-可能存在
h1
没有下一个同级的情况

或者您可以搜索
p
next sibling(这与以前的版本不同):

是一个生成器,它将匹配所有下一个同级,而您需要一个:

tag.name == 'h1' and tag.next_sibling and tag.next_sibling.name == "p"
请注意,我们还应用了
标记。next_sibling
真实性检查-可能存在
h1
没有下一个同级的情况

或者您可以搜索
p
next sibling(这与以前的版本不同):


感谢alecxe的积极响应,它就像一个魅力。感谢alecxe的积极响应,它就像一个魅力。