2016-04-10 29 views
1

使用XPath我更新這個教程,因爲它是過時的,以獲得項目:
http://mherman.org/blog/2012/11/05/scraping-web-pages-with-scrapy/#.VwpeOfl96Ul如何在scrapy

應該取每個作業非營利組織在Craigslist列出的鏈接和標題。鏈接被抓取,但標題沒有。

這是頁面的該元素的代碼:

<span class="pl"> 
    <time datetime="2016-04-09 14:10" title="Sat 09 Apr 02:10:57 PM">Apr 9</time> 
    <a href="/nby/npo/5531527495.html" data-id="5531527495" class="hdrlnk"> 
    <span id="titletextonly">Therapist</span> 

這是履帶式的代碼:

def parse(self, response): 
    hxs = HtmlXPathSelector(response) 
    titles = hxs.xpath("//span[@class='pl']") 
    items = [] 
    for titles in titles: 
     item = CraigslistSampleItem() 
     item["title"] = titles.select("a/text()").extract() 
     item["link"] = titles.select("a/@href").extract() 
     items.append(item) 
    return items 

如果我檢查Chrome中的元素,並獲得了XPath,我得到這個標題: // * [@ id ='titletextonly'],但是這給了我所有標題的列表,不僅僅是鏈接的標題(在這種情況下,我應該得到'/ nby/npo/5531527495.html'爲鏈接,'治療師'爲標題)

我知道行

item["title"] = titles.select("a/text()").extract() 

需要更新,但如果我進入//*[@id='titletextonly']我得到的每一個冠軍,所以我接近,但我不知道如何獲得的XPath來「titletextonly」在'href'元素中。

我是Scrapy和Xpath的新手,所以請在你的評論中友好。

謝謝。

回答

1

將Xpath更改爲如下遍歷至'span'標記。

item["title"] = titles.select("a/span/text()").extract() 
+0

也做到了,謝謝! – Tensigh

1

a/text()將僅選擇了a元素的直接子文本元素。您要的文字不是a元素的子元素;它在span之內。

我沒有用過scrapy,但我建議嘗試這樣的:

item["title"] = titles.select("a").extract() 

這應該得到a元素,這將包括所有它裏面的文本的字符串值。

如果不工作,你也可以嘗試:

item["title"] = titles.select("a//text()").extract() 
+0

感謝您提供答案。 – Tensigh