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
或类似的工具一起使用。
如果你使用 BeautifulSoup
和 request
那么你必须自己做所有事情 - 你必须从头开始构建爬虫系统。
Scrapy是真正的爬虫(或者更确切地说是构建蜘蛛和爬网网络的框架)。
它有选项 DEPTH_LIMIT
关于python - 用 BeautifulSoup 爬行深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908372/