2017-10-25 1 views
0

を掻き出していない私はthis siteからデータをこすり取る際には、以下のスクリプトを書きました:がスクラッピデータ

import scrapy 

class MySpider(scrapy.Spider): 
    name = 'jobs' 
    start_urls = ['https://www.freelancer.in/jobs/python_web-scraping_web-crawling/'] 

    def parse(self, response): 

     for title in response.xpath('//div[@class = "JobSearchCard-primary-heading"]//a'): 
      yield{ 
       'title' : title.xpath('a/text()').extract_first() 
      } 

しかし、私はそれを実行したとき、私はタイトルだけを除いて空のファイルを受け取りますか?これはなぜですか?

答えて

1

あなたのXPathセレクターはNoneを返します。それはおそらく次のようになります。さらに

'title' : title.xpath('text()').extract_first()

、あなたは過度のシンボルを取り除くことができます。セレクタは何も見つからなかった場合に例外を回避することを目的と

'title' : title.xpath('text()').extract_first(default='').strip()

default=''

0

これを打つと、そのページからあなたの期待するタイトルが得られなかったと伝えます。定義されたxpathに障害がありました。さらに、各文字列には巨大な空白がありますので、.strip()も必要です。以下のスクリプトは、きれいな出力を提供します。

import scrapy 

class MySpider(scrapy.Spider): 
    name = 'jobs' 
    start_urls = ['https://www.freelancer.in/jobs/python_web-scraping_web-crawling/'] 

    def parse(self, response): 

     for title in response.xpath('//*[@class="JobSearchCard-primary-heading-link"]/text()').extract(): 
      yield{ 
       'title' : title.strip() 
      } 
0

これを試してみてください:

import scrapy 

class MySpider(scrapy.Spider): 
    name = 'jobs' 
    start_urls = ['https://www.freelancer.in/jobs/python_web-scraping_web-crawling/'] 

    def parse(self, response): 
     for title in response.xpath('//div[@class = "JobSearchCard-primary-heading"]//a'): 
      yield { 
       'title' : title.xpath('./text()').extract_first().strip() 
      } 

インナーxpathがループのノードに対して相対的でなければなりません。