python - 用 BeautifulSoup 爬行深度

标签 python python-3.x web-scraping beautifulsoup rcrawler

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

Rcrawler(Website = "https://stackoverflow.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://stackoverflow.com/').read()
print(text_from_html(html))

感谢任何见解或方向。

最佳答案

BeautifulSoup 中没有函数,因为BeautifulSoup 不是爬虫
它只使用 HTML 解析字符串,因此您可以在 HTML 中搜索。

requests 中没有函数,因为requests 也不是crawler
它只从服务器读取数据,因此您可以将它与 BeautifulSoup 或类似的工具一起使用。

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

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

关于python - 用 BeautifulSoup 爬行深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908372/

相关文章:

python - 如何在 mchanize 中使用 Internet Explorer 作为浏览器

python - 使用 BeautifulSoup 从网站获取图像 src

python - 读取csv文件,解析数据,并存储在字典中

将颜色打印到控制台时出现 python 间距问题

python - 如何使用 SQLAlchemy 只创建一张表?

excel - VBA 代码 - 连接到网页并检索值

python - 使用 PyImgur 上传上传的图像,无需保存到临时文件

python - Pandas:如何跟踪两个数据帧之间匹配数据条目的索引?

python - 为什么我得不到并发执行?

python - 单元测试 : same test class with mutliple datasets