2015-10-11 150 views
3

這樣的IM」試圖湊在下面的網站scrapy的SgmlLinkExtractor參數的網站,這是我的蜘蛛是什麼樣子:scrapy蜘蛛碼校驗

from scrapy.spiders import CrawlSpider, Rule 
from scrapy.linkextractors.sgml import SgmlLinkExtractor 
from scrapy.selector import HtmlXPathSelector 
from desidime_sample.items import DesidimeItem 
import string 

class DesidimeSpider(CrawlSpider): 
    name = "desidime" 
    allowed_domains = ["desidime.com"] 
    start_urls = ["http://www.desidime.com/forums/hot-deals-online"] 
    rules = (
     Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('''//td[not(@*)]/div 
     [not(@*)]/a[not(@class)]/@href''')), callback="parse_items", follow=True), 
) 
    def parse_items(self, response): 
     hxs = HtmlXPathSelector(response) 
     deals = hxs.select('''//div[@class='user-comment-text'][1]''') 
     items = [] 
     for deals in deals: 
      item = DesidimeItem() 
      item["deal"] = deals.select("//div[@class='user-comment-text'][1]/p/text()").extract() 
      item["link"] = deals.select("//div[@class='user-comment-text'][1]/p[1]/a[1]/@href").extract() 
      items.append(item) 
     return items 

這應該是很明顯的就是我試圖做的,但由於某些原因,當我告訴蜘蛛抓取並導出的文本和鏈接到CVS文件,我結束了:

鏈接,成交http://wwww.facebook.com/desidimehttp://wwww.facebook.com/desidime, (有更多的線一樣的東西,然後:) 「,,」 , 「同一個URL」, (有更多的線一樣的東西,然後:) 「鏈接,優惠」

所以,誰能告訴我問題是什麼?如果您在scrapy shell "//corresponingcrawlruleurl"之後運行我的上述每個xpath作爲reponse.xpath("xpath").extract(),您將得到正確的結果。

回答

2

問題出在parse_items回調中。在迭代交易時,交易特定於上下文的定位器必須是相對的。換句話說,使用圓點在循環內啓動XPath表達式:

def parse_items(self, response): 
    for deal in response.xpath("//div[@class='user-comment-text'][1]"): 
     item = DesidimeItem() 

     item["deal"] = deal.xpath(".//p/text()").extract() 
     item["link"] = deal.xpath(".//p[1]/a[1]/@href").extract() 

     yield item 

(請注意,我還簡化了代碼)。

下面是完整的蜘蛛,我執行(它刮掉的文本和鏈接,雖然我不知道什麼是你想要的輸出):

import scrapy 
from scrapy.spiders import CrawlSpider, Rule 
from scrapy.linkextractors import LinkExtractor 


class DesidimeItem(scrapy.Item): 
    deal = scrapy.Field() 
    link = scrapy.Field() 


class DesidimeSpider(CrawlSpider): 
    name = "desidime" 
    allowed_domains = ["desidime.com"] 
    start_urls = ["http://www.desidime.com/forums/hot-deals-online"] 

    rules = [ 
     Rule(LinkExtractor(restrict_xpaths="//td[not(@*)]/div[not(@*)]/a[not(@class)]"), 
      callback="parse_items", 
      follow=True), 
    ] 

    def parse_items(self, response): 
     for deal in response.xpath("//div[@class='user-comment-text'][1]"): 
      item = DesidimeItem() 

      item["deal"] = deal.xpath(".//p/text()").extract() 
      item["link"] = deal.xpath(".//p[1]/a[1]/@href").extract() 

      yield item 
+0

我想:「//」是相對的到'response.xpath()中的路徑?我還需要在xpath fo item [「deal」]和item [「link」]中使用'//div[@class='user-comment-text'][1]'嗎? – user3108815

+0

@ user3108815你一定需要點。是的,我也刪除了'// div [@ class ='user-comment-text'] [1]''。請注意,我沒有測試所提供的代碼 - 它只是來自體驗。希望能幫助到你。 – alecxe

+0

明白了,ty。生病讓你知道它是否有效。 – user3108815