在 Scrapy 中利用 Beautifulsoup

Ant*_*ony 2 python parsing beautifulsoup scrapy

我创建了一个简单的爬虫,Scrapy它从给定的链接开始,并跟踪给定内的所有链接,DEPTH_LIMIT每次运行蜘蛛时都会根据项目参数进行调整。为了简单起见,该脚本会打印响应 URL。

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from NONPROF.items import NonprofItem
from scrapy.http import Request
import re

class Nonprof(CrawlSpider):
    name = "my_scraper"
    allowed_domains = ["stackoverflow.com"]
    start_urls = ["https://stackoverflow.com"]

    rules = [
        Rule(LinkExtractor(
            allow=['.*']),
             callback='parse_item',
             follow=True)
        ]

    def parse_item (self, response):
        print (response.url)
Run Code Online (Sandbox Code Playgroud)

我当前的目标是解析从起始 URL 开始的给定深度内的所有可见文本,并使用该数据进行主题建模。我过去使用 做过类似的事情BeautifulSoup,但我想在我的爬虫中利用以下解析语言。

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))
Run Code Online (Sandbox Code Playgroud)

我将两者集成的困难在于BeautifulSoupobject 和Responsefrom背后的逻辑Scrapy

任何意见都会受到赞赏。

ale*_*cxe 5

至少,您可以直接将包含在其中的 HTML 源代码传递response.bodyBeautifulSoup解析:

soup = BeautifulSoup(response.body, "lxml") 
Run Code Online (Sandbox Code Playgroud)

但请注意,虽然这可行并且您可以使用soupHTML 解析所需的数据,但您并没有使用 Scrapy 的大部分 -Scrapy选择器、项目加载器中选择器的使用等。如果我是你,我只会让自己熟悉 Scrapy 从 HTML 中提取数据的强大功能。