【问题标题】:Crawling Depth with BeautifulSoup用 BeautifulSoup 爬行深度
【发布时间】:2017-12-20 14:35:55
【问题描述】:

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 用于解析,而非爬取。我相信Scrapy 在这里很合适。

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


【解决方案1】:

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

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

如果您使用BeautifulSouprequest,那么您必须自己完成所有工作 - 您必须从头开始构建抓取系统。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多