python - BeautifulSoup 标签的出现顺序

标签 python web-scraping beautifulsoup

考虑以下情况:

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/

相关文章:

python - 如何使用 python-magic 通过 Internet 获取文件的文件类型?

python - C 与 Python 中特征向量例程的不同结果

python - 尝试/除了抓取 URL 末尾带有 3 个随机数字的网站

json - Python 和 BeautifulSoup : How to convert JSON into CSV

regex - 如何在python3中组合两个re.compile正则表达式?

python - 没有类或标签的 BeautifulSoup

python - 使用opencv2 python在图像中矩形和正方形之间的区分

python - 使用 Django 模板标签 'slice' 切片 pandas 数据框?

python - scrapy xpath 为什么这个页面是空的,但我可以在 chrome f12 工具中看到它?

python-2.7 - 类型错误 : 'NoneType' object not callable Python with BeautifulSoup XML