【问题标题】:Scrapy encoding and json formatting issueScrapy编码和json格式问题
【发布时间】:2017-05-22 16:14:10
【问题描述】:

我正在使用python 3.6x版本和scrapy提取一些在线数据。

import scrapy

class QuotesSpider(scrapy.Spider):
name = "extract"

start_urls = [
    'https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q10174455955',
]

def parse(self, response):
    question_title = response.css("div.ptsQes P::text").extract_first().strip()
    question_content = response.css("div.ptsQes P.queTxt::text").extract()
    best_answer = response.css("div.mdPstd.mdPstdBA.othrAns.lstLast.clrfx div.ptsQes p.queTxt::text").extract()
    filename = 'extract.json'
    with open(filename, 'wb') as f:
        f.write(question_title.encode("utf8")),
        f.write(question_content[0].encode("utf8")),
        f.write(best_answer[0].encode("utf8"))
    self.log('Saved file %s' % filename)

我尝试从上面编写的代码中提取数据,但遇到了几个问题,如果有人能提供帮助,将不胜感激。

  1. 我怎样才能把它变成 json 格式,即 ['question_title' : 'XXX','question_content':'XXX','best_answer': 'xxx'] 因为我只能得到一些字符串

  2. 为什么我不能把 encode("utf8") 放在 response.css 之后...,即

response.css("div.ptsQes P::text").extract_first().strip().encode("utf8")

它不起作用。 它没有对任何数据进行编码,但将 unicode 留给我。

如果有人知道,谢谢。

【问题讨论】:

  • 你可以看看python编码错误处理here
  • 谢谢,很有帮助

标签: python scrapy


【解决方案1】:

使您的数据 json 格式化。我会使用内置的 json 库。

import json
json.dumps({'question_title' : question_title,
            'question_content':'question_content',
            'best_answer': 'best_answer'}).encode('utf8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2023-04-09
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多