2014-12-01 162 views
1

我正在使用scrapy外殼來提取一些文本數據。以下是我在scrapy外殼上給出的命令:Scrapy response.xpath不返回任何查詢

>>> scrapy shell "http://jobs.parklandcareers.com/dallas/nursing/jobid6541851-nurse-resident-cardiopulmonary-icu-feb2015-nurse-residency-requires-contract-jobs" 

>>> response.xpath('//*[@id="jobDesc"]/span[1]/text()') 
[<Selector xpath='//*[@id="jobDesc"]/span[1]/text()' data=u'Dallas, TX'>] 
>>> response.xpath('//*[@id="jobDesc"]/span[2]/p/text()[2]') 
[<Selector xpath='//*[@id="jobDesc"]/span[2]/p/text()[2]' data=u'Responsible for attending assigned nursi'>] 
>>> response.xpath('//*[@id="jobDesc"]/span[2]/p/text()[preceding-sibling::*="Education"][following-sibling::*="Certification"]') 
[] 

第三個命令沒有返回任何數據。我試圖在命令中的2個關鍵字之間提取數據。我在哪裏錯了?

回答

1

//*[@id="jobDesc"]/span[2]/p/text()會返回給你一個文本節點列表。您可以使用Python過濾相關節點。這裏是你如何能得到之間的文本 「教育/經驗:」「認證/註冊/執照:」文本段落:

>>> result = response.xpath('//*[@id="jobDesc"]/span[2]/p/text()').extract() 
>>> start = result.index('Education/Experience:') 
>>> end = result.index('Certification/Registration/Licensure:') 
>>> print ''.join(result[start+1:end]) 
- Must be a graduate from an accredited school of Nursing. 

UPD(關於評論的附加題):

>>> response.xpath('//*[@id="jobDesc"]/span[3]/text()').re('Job ID: (\d+)') 
[u'143112'] 
+0

我在這個問題中有一個更多的小查詢。我試過這樣的東西:>>> jid = response.xpath('// * [@ id =「jobDesc」]/span [3]/text()')。extract()....我試過只提取數字並刪除「作業ID:」...但開始不會以同樣的方式工作..索引不在列表中 – Abhishek 2014-12-02 17:31:17

+1

@crozzfire當然,這是['.re( )'](http://doc.scrapy.org/zh/latest/topics/selectors.html#using-selectors-with-regular-expressions),請參閱答案中的更新。 – alecxe 2014-12-02 18:05:16

0

嘗試:

substring-before(
    substring-after('//*[@id="jobDesc"]/span[2]/p/text()', 'Education'), 'Certification') 

注:我無法測試它。

這個想法是,你不能使用preceding-siblingfollowing-sibling,因爲你看在同一個文本節點。必須使用substring-before()substring-after()

提取所需的文本部分。通過組合這兩個函數,可以選擇介於兩者之間的內容。