首页 > 解决方案 > Python / Scrapy:如何确定页面是否为html?

问题描述

我需要确定 Scrapy 蜘蛛下载的页面是否为 html。我希望蜘蛛抓取的网站有 pdf 和 html 链接的组合。因此,如果遇到 pdf 文件,它将通过 PDFReader 发送响应,否则它将按原样读取 html 文件。这是我的代码的一部分,但它不起作用:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "spyder_OLD"
    allowed_domains = ['doc.scrapy.org']
    start_urls = ['https://doc.scrapy.org/en/latest/index.html']

    def parse(self, response):
        ct = response.headers.get("content-type", "").lower()
        return ct

我将蜘蛛的结果输出到 .csv 文件,但它始终为空。只是ct = response.headers输出整个头信息,这是没用的。我该怎么办?

编辑: 我终于设法返回字典,但仍然无法提取相关信息:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "spyder_OLD"
    allowed_domains = ['doc.scrapy.org']
    start_urls = ['https://doc.scrapy.org/en/latest/index.html']

    def parse(self, response):
        ct = {"content-type": response.headers.get("content-type", "").lower()}
        return ct["content-type"]

将上述内容输出到 .csv 文件仍会返回一个空白文件,但会output ct返回一个包含两行的 .csv 文件:content-typetext/html. 如何仅提取答案的“html”文本部分?

标签: pythonhtmlscrapy

解决方案


不确定它是否还在。但听起来 builtwith 模块可能对你有用?

它向您展示了正在实现的各种 javascript 框架、Web 框架和 Web 服务器。您可以搜索网络框架并确定它们是否用于动态加载内容。

您可以: pip install builtwith

https://pypi.org/project/builtwith/1.3.3/


推荐阅读