考虑以下情况:
tag1 = soup.find(**data_attrs)
tag2 = soup.find(**delim_attrs)
有没有办法找出页面中“第一个”出现的标签?
澄清:
- 就我的目的而言,顺序与 beautifulsoup 的 findNext 方法相同。 (我目前正在利用这个事实来“解决”我的问题,尽管它很hacky。)
- 这里的目的基本上是累积不被“分隔符标签”分隔的标签。也许有更好的方法来做到这一点?
最佳答案
BeautifulSoup 标签不会跟踪它们在页面中的顺序,不是。您必须再次循环遍历所有标签,并在该列表中找到您的两个标签。
使用标准sample BeautifulSoup tree :
>>> tag1 = soup.find(id='link1')
>>> tag2 = soup.find(id='link2')
>>> tag1, tag2
(<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>)
>>> all_tags = soup.find_all(True)
>>> all_tags.index(tag1)
6
>>> all_tags.index(tag2)
7
我会使用 tag.find_all()
和一个函数来匹配两种标签类型;这样您就可以获得标签列表并可以看到它们的相对顺序:
tag_match = lambda el: (
getattr(el, 'name', None) in ('tagname1', 'tagname2') and
el.attrs.get('attributename') == 'something' and
'classname' in el.attrs.get('class')
)
tags = soup.find(tag_match)
或者您可以使用 .next_siblings
迭代器循环同一父级中的所有元素,并查看下一个是否是分隔符,等等。
关于python - BeautifulSoup 标签的出现顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675869/