2017-12-27 290 views
0

我正在按照教程使用scrapy庫從網站上刮掉多個頁面。本教程使用yield語句通過css選擇器和xpath選擇器從頁面的html和css結構中獲取信息。我決定使用if語句來檢查搜索查詢是否找到結果,並使用else語句來輸出當搜索查詢沒有遇到結果時要執行的操作。當代碼執行提取公司名稱的else語句,以及位置和銷售字段時,我想要一個傳達'未找到'的自定義輸出字符串時出現問題。使用Yield語句返回輸出,當使用scrapy沒有發現搜索查詢時python

當我運行該腳本,我得到以下錯誤:

File "C:\Users\....\hoover-scraper\scraper.py", line 28 

'Location': 'Not Found' 
     ^

我覺得這是不使用yield語句,這就是爲什麼我收到的SyntaxError消息的正確方法。因此,我想知道在查詢遇到空搜索時,是否有任何方法可以爲銷售和位置字段輸出字符串「未找到」。

我的這部分代碼:

def parse(self, response): 
    NAME_SELECTOR ="td a::text" 
    LOCATION_SELECTOR ='.//tr/td/text()' #using xpath to grab information for Location and Sales 
    SALES_SELECTOR = './/tr/td/text()' 

if response.css(NAME_SELECTOR).extract_first(): #Checks to see if the company name field has data if not prints 'No results found' 
     yield { 

      'Company Name': response.css(NAME_SELECTOR).extract_first(), 
      'Location' : response.xpath(LOCATION_SELECTOR)[0].extract(), #Location comes first inside the td tags thus the [0] 
      'Sales' : response.xpath(SALES_SELECTOR)[1].extract(), 
     } 

    else: 
     yield { 
      'Company Name': response.css("dd.value.term::text").extract_first() #identifies company name which data was not found 
      'Location': 'Not Found' 
      'Sales': 'Not Found' 
     } 
+0

參見:https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do – MrT

回答

2

yield僅用於發電。你只是想從你的方法中返回這個價值嗎?然後在兩個地方將yield替換爲return

如果您需要稍後在同一個方法中使用該值,請將字典分配給一個變量。像

if response.css(NAME_SELECTOR).extract_first(): #Checks to see if the company name field has data if not prints 'No results found' 
     result = { 

      'Company Name': response.css(NAME_SELECTOR).extract_first(), 
      'Location' : response.xpath(LOCATION_SELECTOR)[0].extract(), #Location comes first inside the td tags thus the [0] 
      'Sales' : response.xpath(SALES_SELECTOR)[1].extract(), 
     } 

    else: 
     result = { 
      'Company Name': response.css("dd.value.term::text").extract_first(), #identifies company name which data was not found 
      'Location': 'Not Found', 
      'Sales': 'Not Found' 
     } 
    # do something with result 
    ... 
    # or just: 
    return result 
+0

是的,我以後需要使用這些值,所以將它們轉換爲一個字典的作品爲了我。我在else語句中的每個字典條目之後添加了昏迷,並且它工作正常。 –

相關問題