2012-12-16 66 views
1

這是我的代碼Scrapy不回工作,併產生共同

def parse(self, response): 
    soup = BeautifulSoup(response.body) 
    hxs = HtmlXPathSelector(response) 
    sites = hxs.select('//div[@class="row"]') 
    items = [] 

    for site in sites[:5]: 
     item = TestItem() 
     item['username'] = "test5" 
     request = Request("http://www.example.org/profile.php", callback = self.parseUserProfile) 
     request.meta['item'] = item 
     **yield item** 

    mylinks= soup.find_all("a", text="Next") 
    if mylinks: 
     nextlink = mylinks[0].get('href') 
     yield Request(urljoin(response.url, nextlink), callback=self.parse) 

def parseUserProfile(self, response): 
    item = response.meta['item'] 
    item['image_urls'] = "test3" 
    return item 

現在我的上述作品,但與我沒有得到的item['image_urls'] = "test3"

它即將爲空現在

值如果使用return request而不是yield item

然後得到錯誤cannot use return with generator

如果我刪除此行

yield Request(urljoin(response.url, nextlink), callback=self.parse) 然後我的代碼工作正常,我可以得到image_urls但後來我canot按照鏈接

那麼,有沒有辦法讓我可以使用return requestyield together等等我得到的item_urls

+0

如果你使用'yield'你讓你的函數發生器,這是你的錯誤是告訴你。 'parseUserProfile'中定義的'item'在哪裏?它是一個類變量。 – Blender

+0

@Blender我忘了在這裏添加,我從meta迴應。所以我該怎麼做才能解決我的問題。我在我的問題中添加了 – user1858027

+0

對於我的Scrapy應用程序,我一直只在回調函數中使用'yield'語句,並且一切正常。你有沒有嘗試在'parseUserProfile'中用'yield item'替換'return item'? – pemistahl

回答

1

我真的不明白你的問題,但我看到你的代碼一個問題:

def parseUserProfile(self, response): 
    item = response.meta['item'] 
    item['image_urls'] = "test3" 
    return item 

解析回調返回值應該序列,所以你應該做return [item]或回調轉換爲發電機:

def parseUserProfile(self, response): 
    item = response.meta['item'] 
    item['image_urls'] = "test3" 
    yield item 
+0

我試過了evrything,yield item也在工作,但我的問題是我的邏輯返回items和獲得下一個鏈接的功能是相同的。所以無論我應該'返回項目'這是在頁面解析或我應該返回'請求'爬行下一個鏈接。在crawlspider規則的事情自動摺疊鏈接鏈接,他們從鏈接提取,但在basespider我不得不手動獲取鏈接,並按照他們手動。這是我在問題 – user1858027

1

看起來你有一個機械故障。相反的:

for site in sites[:5]: 
    item = TestItem() 
    item['username'] = "test5" 
    request = Request("http://www.example.org/profile.php", callback = self.parseUserProfile) 
    request.meta['item'] = item 
    **yield item** 

您需要:

for site in sites[:5]: 
    item = TestItem() 
    item['username'] = "test5" 
    request = Request("http://www.example.org/profile.php", callback = self.parseUserProfile) 
    request.meta['item'] = item 
    yield request 
+0

與我沒有得到scrapy返回的任何項目。我只是在數據庫中獲得一個條目。我沒有得到任何錯誤,爬蟲運行正常,但scrapy沒有得到任何項目旁邊的第一項。我們非常接近解決這個問題,因爲我沒有得到任何錯誤。我甚至嘗試把產量項放在parseuserprofile中,但它又不返回任何項目 – user1858027

+0

正確返回項目的唯一方法是返回請求,但是我不能使用第二個yield。 – user1858027

+0

和'parseUserProfile'放'yield item' – warvariuc