2016-06-24 2 views
0

페이지 (예 : 페이스 북, 트위터 등)에서 소셜 네트워크 프로필 URL을 캡처하는 치료 프로그램을 작성 중입니다.Scrapy/Python - 누락 된 데이터를 처리하는 방법은 무엇입니까?

내가 긁은 페이지 중 일부는 링크가 없어 프로그램이이를 처리 할 수 ​​있어야합니다.

나는 링크 페이지에있을 때 트위터 프로필 링크를 찾지 만 링크 페이지에없는 경우 실패 코드 줄이 있습니다

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 
+0

'try'와'except'를? – dagrha

답변

2

대신 .extract()[0].extract_first() 방법을 사용합니다. 추출 할 것이 없을 때 None을 반환합니다.

그래서, 대신 :

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

당신은이 것 :

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

그게 - 고마워 :) – user1287245

관련 문제