2016-06-24 4 views
0

私はページからソーシャルネットワークプロファイルのURLをキャプチャするプログラム(例えば、Facebook、twitterなど)を作成しています。Scrapy/Python - 欠けているデータをどう扱うのですか?

私が掻き取ったページのいくつかは、それらのリンクを持っていないので、プログラムはそれに対処できる必要があります。

私はリンクがページ上にあるが、リンクがページ上にないときに失敗したときに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 
+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

関連する問題