python - 在 Scrapy 中利用 Beautifulsoup

标签 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)

我当前的目标是从起始 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))

我将两者集成的困难在于 BeautifulSoup 对象和来自 ScrapyResponse 背后的逻辑。

欢迎任何意见。

最佳答案

至少,您可以将 response.body 中包含的 HTML 源直接传递给 BeautifulSoup 进行解析:

soup = BeautifulSoup(response.body, "lxml") 

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

关于python - 在 Scrapy 中利用 Beautifulsoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48086330/

相关文章:

php - 解析希伯来语 XML

c# - 用于平衡嵌套括号的 super 解析器

java - 使用 simpleDateFormat java 解析日期

python - 为什么 Beautiful Soup 找不到具有多个类的这个元素?

python - sqlite3 : create function regexp with python

python - 删除 python 然后在 Mac OSX 上重新安装

python - 将值放在矩阵中的随机位置

python - 在 Python 中处理传递性

python-2.7 - 如何使用 BeautifulSoup 从 Python 中的字符串中删除 html 标签

python - 使用 Python 进行网页抓取 - 选择 div、h2 和 h3 类