2016-09-27 2 views
1
나는이 website에서 일부 데이터를 긁어 할

, 내 거미 코드는 다음과 같습니다파이썬 XPath는 선택이 점점 오류

# -*- coding: utf-8 -*- 
import scrapy 
from coder.items import CoderItem 
# from scrapy.loader import ItemLoader 


class LivingsocialSpider(scrapy.Spider): 
    name = "livingsocial" 
    allowed_domains = ["livingsocial.com"] 
    start_urls = (
     'http://www.livingsocial.com/cities/15-san-francisco', 
    ) 

    def parse(self, response): 
     # deals = response.xpath('//li') 
     for deal in response.xpath('//li/a//h2'): 
      item = CoderItem() 
      item['title'] = deal.xpath('text()').extract_first() 
      yield item 

그것은 잘 작동하지만 문제는 내가

for deal in response.xpath('//li'): 
    item = CoderItem() 
    item['title'] = deal.xpath('a//h2/text()').extract_first() 
    yield item 

이로 변경할 때 , 아무 것도 반환하지 않습니다! 그게 같지 않니?

답변

2

response.xpath("//li")의 일부 노드에는 그 아래에 a 노드가 없으므로 제목이 없기 때문에 빈 항목을 얻을 수 있습니다. 지금 모든 항목 노드 항목을 가지고 볼 수 있듯이

items = response.xpath('//li[a//h2/text()]') 
len(items) 
# 1019 
titles = [i.xpath("a//h2/text()").extract_first() for i in items] 
len([t for t in titles if t]) 
# 1019 

: 당신이 할 수있는 일

대신이 XPath를 사용합니다.

+0

감사합니다. 매력처럼 작동합니다. D – Mohib