我的任务是查找文章的正文<div id="bodyContent">
,并在其中计算最大链接序列的长度,在这个链接之间没有其他标签打开或关闭。例如:
<p>
<span><a></a></span>
**<a></a>
<a></a>**
</p>
- 连续有2个链接,因为关闭范围会中断序列。
<p>
**<a><span></span></a>
<a></a>
<a></a>**
</p
- 并且子系列有3个链接,因为span位于链接内部,而不是链接之间。为了解决这个问题,我正在使用beautifulsoup和python。
码:
import requests
from bs4 import BeautifulSoup
html = requests.get('https://en.wikipedia.org/wiki/Stone_Age')
soup = BeautifulSoup(html.text, "lxml")
body = soup.find(id="bodyContent")
# get first link
first_link = body.a
# find all links that are in the same level
first_link.find_next_siblings('a')
如何转到以下链接?
最好的祝福!
我的解决方案是:
import requests
from bs4 import BeautifulSoup
html = requests.get('https://en.wikipedia.org/wiki/Stone_Age')
soup = BeautifulSoup(html.text, "lxml")
body = soup.find(id="bodyContent")
tag = body.find_next("a")
linkslen = -1
while (tag):
curlen = 1
for tag in tag.find_next_siblings():
if tag.name != 'a':
break
curlen += 1
if curlen > linkslen:
linkslen = curlen
tag = tag.find_next("a")
print(linkslen)