如果一个页面有10个链接,网站上有5个页面深度(中等规模网站的主流深度),如果要采集整个网站,一共需要采集的网页数量就是10^5,即100000个页面,因为很少有网站会涉及到这么多的网页,因为有很大一部分是因为网页重复的原因,为了避免采集两次,链接去重很重要
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages=set()
def getLinks(pageUrl):
global pages
html=urlopen("https://en.wikipedia.org"+pageUrl)
bsObj=BeautifulSoup(html) #创建一个BeautifulSoup对象
for link in bsObj.findAll("a",href=re.compile("^(/wiki/)")):
if 'href' in link.attrs: #找出link的所有属性,判断"href"这个开头为wiki是否在这个字典里
if link.attrs['href'] not in pages:
#我们遇到了新的页面
newPage=link.attrs['href']
print(newPage)#打印出新的页面
pages.add(newPage)#加入到全局变量的集合中
getLinks(newPage)#递归处理新的链接
getLinks("") #空的url