BeautifulSoup 的爬行深度

Crawling Depth with BeautifulSoup

beautifulsoup 包中是否有允许用户设置站点内抓取深度的功能?我对 Python 比较陌生,但我之前在 R 中使用过 Rcrawler,Rcrawler 提供 'MaxDepth' 因此爬虫将进入该域内主页的一定数量的链接。

Rcrawler(Website = "https://whosebug.com/", no_cores = 4, no_conn = 4, ExtractCSSPat = c("div"), ****MaxDepth=5****)

Python 中我当前脚本的基础是解析页面上的所有可见文本,但我想设置抓取深度。

from bs4 import BeautifulSoup
import bs4 as bs
import urllib.request

def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    elif isinstance(element,bs.element.Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(html, 'lxml')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return u" ".join(t.strip() for t in visible_texts)

html = urllib.request.urlopen('https://whosebug.com/').read()
print(text_from_html(html))

如有任何见解或方向,我们将不胜感激。

BeautifulSoup 中没有函数,因为 BeautifulSoup 不是 crawler
它只解析带有 HTML 的字符串,因此您可以在 HTML.

中搜索

requests中没有函数,因为requests也没有crawler
它仅从服务器读取数据,因此您可以将其与 BeautifulSoup 或类似的方法一起使用。

如果您使用 BeautifulSouprequest 那么您必须自己做所有事情 - 您必须从头开始构建爬虫系统。

Scrapy 是真正的爬虫(或者更确切地说是构建蜘蛛和爬网网络的框架)。
它有选项 DEPTH_LIMIT