AttributeError:“SelectorList”对象没有属性“replace”

2024-06-01 00:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试运行一个Scrapy spider并将其全部转储到一个json文件中。我的代码是:

import scrapy
import re


class MissleItem(scrapy.Item):

    missle_name = scrapy.Field()
    missle_type = scrapy.Field()
    missle_origin = scrapy.Field()
    missle_range = scrapy.Field()
    missle_comments = scrapy.Field()



class missleSpider(scrapy.Spider):

    name = 'missle_list'
    allowed_domains = ['en.wikipedia.org']
    start_urls = ['https://en.wikipedia.org/wiki/...']


    def parse(self, response):
        table = response.xpath('///div/table[2]/tbody')
        rows = table.xpath('//tr')
        row = rows[2]
        row.xpath('td//text()')[0].extract()

        for row in response.xpath('// \
        [@class="wikitable"]//tbody//tr'):

            name = {
            'Missle' : row.xpath('td[1]//text()').extract_first(),
            'Type': row.xpath('td[2]//text()').extract_first(),
            'Origin' : 
            row.xpath('td[3]/a//text()').extract_first(), 
            'Range': 
            row.xpath('td[4]//text()').replace(u'\ ', u' 
            ').extract_first(),  
            'Comments' : 
            row.xpath('td[5]//text()').extract_first()}


            yield MissleItem(missle_name=name['Missle'], 
                            missle_type=name['Type'], 
                            missle_origin=name['Origin'], 
                            missle_range=name['Range'], 
                            missle_comments=name['Comments'])

当我运行前面的代码时,我得到: AttributeError:“SelectorList”对象没有属性“replace”

我的问题是,在没有“nbsp;”额外输出的情况下,如何返回范围列?我试过了:

^{pr2}$

但后来我得到一个:

AttributeError: 'SelectorList' object has no attribute 'strip'

任何帮助都将不胜感激


Tags: 代码textnameimportfieldresponsetableextract