在 scrapy response.xpath 上处理错误 json.loads

handle error json.loads on scrapy response.xpath

我尝试使用以下命令从网站使用 scrapy 获取数据:

jsondata = response.xpath('//script[@type="application/ld+json"]/text()').extract_first()
microdata = json.loads(jsondata)   
author = microdata["author"]["name"]
editor = microdata["editor"]["name"]
daten = microdata["datePublished"]

但是如果 json 部分 "//script[@type="application/ld+json"]/text()" 在网站。

感谢您的帮助

import scrapy
import json

class RefSpider(scrapy.Spider):
    name = "refspider"

    start_urls = ['https://www.antaranews.com/berita/2320530/gempa-di-padang-lawas-utara-dipicu-oleh-aktivitas-sesar-sumatera',
                  'https://www.antaranews.com/foto/2320526/penjualan-pernak-pernik-hiasan-kemerdekaan']

    def parse(self, response):
        jsondata = response.xpath('//script[@type="application/ld+json"]/text()').extract_first()

        if jsondata is not None:
            microdata = json.loads(jsondata)
            author = microdata["author"]["name"]
            editor = microdata["editor"]["name"]
            daten = microdata["datePublished"]