【问题标题】:Scrapy, How can I handle missign data between tags using CSS selector? [closed]Scrapy,如何使用 CSS 选择器处理标签之间的缺失数据? [关闭]
【发布时间】:2018-05-19 06:28:48
【问题描述】:

我正在使用 scrapy 从站点列表中抓取数据,为此我正在使用 css 选择器。

数据是这样的:

Name : John Doe
Address : Earth
Age : 30

而html结构是:

<li class='title>
   <span class='q'>Name</span>
   <span class='ans>John Doe</span>
   <br>
   <span class='q'>Address</span>
   <span class='ans>Earth</span>
   <br>
   <span class='q'>Age</span>
   <span class='ans>30</span>
   <br>
</li>

问题是有的,有的地址是空的。 &lt;span class='ans'&gt;&lt;/span&gt; 之间什么都没有。我该如何处理?对于具有适当结构的地址,报废的数据也应为空。

这是我的代码:

'   class NmcSpider(scrapy.Spider):
name = 'nmc'
allowed_domains = ['nmc.org.np']
start_urls = ['http://nmc.org.np/registered-practitioner.html']

def parse(self, response):
    self.log('hello' +response.url)
    for title in response.css('li.title'):
        try:
            item = {
                'name': title.css('span.Ans::text').extract()[0],
                'address': title.css('span.Ans::text').extract()[1],
                'gender': title.css('span.Ans::text').extract()[2],
                'degree': title.css('span.Ans::text').extract()[3],
                'nmc_no':title.css('span.Ans::text').extract()[4]
            }
        except:
            print("No data")
        yield item    '

【问题讨论】:

  • 你的意思是 Scrapy 对待空跨度和处理内容的跨度不同?以什么方式?
  • 是的,它从最近的跨度中获取数据并将其放在那里。如果缺少地址,则输出类似于名称,并且在地址字段中,使用年龄并且没有年龄字段。我想要姓名,如果地址为空,则应显示为空或 Null 和年龄
  • 您希望我们重新为您创建一个刮板吗?如果没有,那么你最好用你的错误脚本@the new guy 更新你的帖子。
  • 如果你能告诉我如何处理标签之间丢失的数据?
  • 尝试使用 XPath 而不是 CSS 选择器:'name': title.xpath('//span[.="Name"]/following-sibling::span[1]/text()').extract(), 'address': title.xpath('//span[.="Address"]/following-sibling::span[1]/text()').extract() ...

标签: python web-scraping scrapy css-selectors


【解决方案1】:

如果您将使用 XPath 表达式,则无需使用 try/except

for title in response.css('li.title'):
    item = {
        'name': title.xpath('.//span[.="Name"]/following-sibling::span[1]/text()').extract_first(),
        'address': title.xpath('.//span[.="Address"]/following-sibling::span[1]/text()').extract_first(),
    }

更新 这是完整的代码(经过测试):

def parse(self, response):
    self.log('hello' +response.url)
    for section in response.xpath('//ul[@id="ImgcategoryCardiologist"]/li'):
            item = {
                'name': section.xpath('.//span[.="Name"]/following-sibling::span[1]/text()').extract_first(),
                'address': section.xpath('.//span[.="Address"]/following-sibling::span[1]/text()').extract_first(),
            }
            yield item

【讨论】:

  • 即使在删除 _first() 之后,它也只废弃了第一个数据
  • 我是初学者,如果你能解释一下 span[1] 在做什么,以及如何提取每个数据。我尝试了代码,它只提取了单个列表。
  • @the-new-guy 我不知道你在说什么。查看我更新的代码,它适用于我
  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 2021-03-24
  • 2018-04-04
  • 2015-10-27
  • 1970-01-01
相关资源
最近更新 更多