【问题标题】:Python/Scrapy: How to determine if a page is html or not?Python / Scrapy:如何确定页面是否为html?
【发布时间】:2018-09-23 12:42:58
【问题描述】:

我需要判断 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”文本部分?

【问题讨论】:

  • 不确定是不是Content-Type: ????
  • 不,这行不通。

标签: python html scrapy


【解决方案1】:

Scrapy 期望你从你的 parse 方法中返回一个项目。它可以是 dict 或 Item object

如果您对 Content-Type 感兴趣:

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

Scrapy 有一个非常好的教程。值得花点时间关注它:https://doc.scrapy.org/en/latest/intro/tutorial.html

编辑:

您可以在 response.text 属性中找到 HTML 代码。但通常,您只需要这段代码。所以,更好的方法是使用选择器。例如,要仅获取 sn-p <h1>Hello world</h1> 中的文本,您可以使用:

title = response.css('h1::text').get()
return {'title': title}

花点时间阅读documentation page about selectors。值得投资。

【讨论】:

  • 嗨,谢谢你,但我如何只返回答案的“html”部分?
  • 嗨,这很好 - 但是我如何在 {'title': title} 字典中获取标题数据?字典['title']的普通python方法不起作用。
  • 它将成为导出文件中的一列。例如。通过运行scrapy runspider spiyder.py -o items.csv
【解决方案2】:

您可以使用 lxml 模块并将文本导入为 html。如果它成功解析它,那么它就是 HTML。

from lxml import etree

我正在打电话,所以我不能给你一个完整的例子。 etree.parse 是你想要的方法。

【讨论】:

    【解决方案3】:

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

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

    你可以:pip install builtwith

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

    【讨论】:

      猜你喜欢
      • 2010-09-24
      • 2019-05-22
      • 2018-01-02
      • 2018-10-13
      • 2012-01-16
      • 2013-05-07
      • 1970-01-01
      • 2021-09-15
      • 2014-01-04
      相关资源
      最近更新 更多