【问题标题】:Scrapy/Python - How deal with missing data?Scrapy/Python - 如何处理丢失的数据?
【发布时间】:2016-06-25 03:59:49
【问题描述】:

我正在编写一个从页面(例如 facebook、twitter 等)捕获社交网络配置文件 URL 的 scrapy 程序。

我抓取的某些页面上没有这些链接,因此程序需要能够处理。

我有这行代码,当链接在页面上时找到 Twitter 个人资料链接,但当链接不在页面上时失败:

item['twitterprofileurl'] = startupdetails.xpath("//a[contains(@href,'https://twitter.com') and not(contains(@href,'https://twitter.com/500startups'))]/@href").extract()[0]

如果链接不存在,我该如何更改它以使代码不会失败?

完整代码:

import scrapy
from scrapy import Spider
from scrapy.selector import Selector
import datetime
from saas.items import StartupItemTest


class StartupSpider(Spider):
    name = "500cotest"
    allowed_domains = ["500.co"]
    start_urls = [
        "http://500.co/startup/chouxbox/"
    ]

    def parse(self, response):
        startup = Selector(response).xpath('//div[contains(@id, "startup_detail")]')

        for startupdetails in startup:
            item = StartupItemTest()
            item['logo'] = startupdetails.xpath('//img[@class="logo"]/@src').extract()[0]
            item['startupurl'] = startupdetails.xpath('//a[@class="outline"]/@href').extract()[0]
            item['source'] = '500.co'
            item['datetime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            item['description'] = startupdetails.xpath("//p[@class='description']/text()").extract()[0]

            item['twitterprofileurl'] = startupdetails.xpath("//a[contains(@href,'https://twitter.com') and not(contains(@href,'https://twitter.com/500startups'))]/@href").extract()[0]
            yield item

【问题讨论】:

  • tryexcept?

标签: python scrapy


【解决方案1】:

使用.extract_first() 方法代替.extract()[0]。当没有可提取的内容时,它会返回 None

所以,而不是:

item['twitterprofileurl'] = startupdetails.xpath("<your xpath>").extract()[0]

你会有:

item['twitterprofileurl'] = startupdetails.xpath("<your xpath>").extract_first()

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2015-06-18
    • 2015-05-31
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多