【问题标题】:Scrapy: Save response.body as html file?Scrapy:将 response.body 保存为 html 文件?
【发布时间】:2017-09-06 05:15:11
【问题描述】:

我的蜘蛛可以工作,但我无法下载我在 .html 文件中抓取的网站的正文。如果我写 self.html_fil.write('test') 那么它工作正常。我不知道如何将 tulpe 转换为字符串。

我使用 Python 3.6

蜘蛛:

class ExampleSpider(scrapy.Spider):
    name = "example"
    allowed_domains = ['google.com']
    start_urls = ['http://google.com/']

    def __init__(self):
        self.path_to_html = html_path + 'index.html'
        self.path_to_header = header_path + 'index.html'
        self.html_file = open(self.path_to_html, 'w')

    def parse(self, response):
        url = response.url
        self.html_file.write(response.body)
        self.html_file.close()
        yield {
            'url': url
        }

追踪:

Traceback (most recent call last):
  File "c:\python\python36-32\lib\site-packages\twisted\internet\defer.py", line
 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "c:\Users\kv\AtomProjects\example_project\example_bot\example_bot\spiders
\example.py", line 35, in parse
    self.html_file.write(response.body)
TypeError: write() argument must be str, not bytes

【问题讨论】:

  • 试试 response.body.decode("utf-8")

标签: python django scrapy web-crawler


【解决方案1】:

实际问题是您正在获取字节码。您需要将其转换为字符串格式。有很多方法可以将字节转换为字符串格式。 你可以使用

 self.html_file.write(response.body.decode("utf-8"))

而不是

  self.html_file.write(response.body)

你也可以使用

  self.html_file.write(response.text)

【讨论】:

  • 我建议使用 response.text,它已经是 Unicode(因为编码可能不是 UTF-8),而不是 response.body.decode("utf-8")
【解决方案2】:

正确的方法是使用response.text,而不是response.body.decode("utf-8")。引用documentation:

请记住,Response.body 始终是一个字节对象。如果您想要 unicode 版本,请使用 TextResponse.text(仅在 TextResponse 和子类中可用)。

文本:响应正文,作为 unicode。

response.body.decode(response.encoding)相同,但在第一次调用后会缓存结果,因此可以多次访问response.text而无需额外开销。

注意:unicode(response.body) 不是将响应正文转换为 unicode 的正确方法:您将使用系统默认编码(通常为 ascii)而不是响应编码。

【讨论】:

    【解决方案3】:

    考虑到上面的响应,并使其尽可能多地 pythonic 添加with 语句的使用,示例应重写为:

    class ExampleSpider(scrapy.Spider):
        name = "example"
        allowed_domains = ['google.com']
        start_urls = ['http://google.com/']
    
        def __init__(self):
            self.path_to_html = html_path + 'index.html'
            self.path_to_header = header_path + 'index.html'
    
        def parse(self, response):
            with open(self.path_to_html, 'w') as html_file:
                html_file.write(response.text)
            yield {
                'url': response.url
            }
    

    html_file 只能通过parse 方法访问。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 2014-01-22
      • 2020-06-24
      相关资源
      最近更新 更多