目标是使用BeautifulSoup查找两个标记之间的距离,例如第一个外部的href属性和title标记。
html = '<title>stackoverflow</title><a href="https://stackoverflow.com">test</a>'
soup = BeautifulSoup(html)
ext_link = soup.find('a',href=re.compile("^https?:",re.IGNORECASE))
title = soup.title
dist = abs_distance_between_tags(ext_link,title)
print dist
30
在不使用regex的情况下,我如何做到这一点?
注意,标记的顺序可能不同,可能有多个匹配(虽然我们只使用了第一个使用find() )。
我无法在BeautifulSoup中找到返回匹配的html中的位置/位置的方法。
发布于 2014-04-14 18:13:48
发布于 2020-12-12 01:58:48
美丽的汤4现在支持Tag.sourceline
和Tag.sourcepos
。
参考资料:https://beautiful-soup-4.readthedocs.io/en/latest/#line-numbers
https://stackoverflow.com/questions/23072773
复制