2014-05-16 104 views
1

我需要從給出錨定標記的特定文本的href屬性中提取url。使用Xpath提取錨定標記的href給定文本

from scrapy.spider import Spider 
from scrapy.selector import Selector 
from nba.items import NBAItem 

class ESPNSpider(Spider): 
    name = "ESPN" 
    allowed_domains = ["espn.com"] 
    start_urls = ["http://espn.go.com/nba/teams"] 

def parse(self, response): 
    sel = Selector(response) 
    sites = sel.xpath('//*[@id="content"]/div[3]/div[1]') 
    items = [] 
    for site in sites: 
     item = NBAItem() 
     item['team_name'] = site.xpath('//a[@class="bi"]/text()').extract() 
     item['team_link'] = site.xpath('//a[@class="bi"]/@href').extract() 
     item['team_stats_link'] = site.xpath('//a[text()='Stats']/@href').extract() 
     items.append(item) 
    return items 

這是我遇到的麻煩線路:

item['team_stats_link'] = site.xpath('//a[text()='Stats']/@href').extract() 

我也嘗試:

item['team_stats_link'] = site.xpath('//a[contains(text(), 'Stats')]/@href).extract() 

相關網站:http://espn.go.com/nba/teams

+0

'site.xpath('// a [text()='Stats']/@ href')'是一個Python語法錯誤。看看單引號。 – Tomalak

+0

啊!一直以來。感謝您的幫助。 – user1636797

回答

1

你裏面的XPath循環應該以.//開頭,換句話說,您需要使其相關給site

我還經歷li標籤ulmedium-logos類中,而不是與content ID的div內第三div裏面搜索第一個div

class ESPNSpider(Spider): 
    name = "ESPN" 
    allowed_domains = ["espn.com"] 
    start_urls = ["http://espn.go.com/nba/teams"] 

    def parse(self, response): 
     sel = Selector(response) 
     sites = sel.xpath('//ul[@class="medium-logos"]//li') 
     for site in sites: 
      item = NBAItem() 
      item['team_name'] = site.xpath('.//a[@class="bi"]/text()').extract()[0] 
      item['team_link'] = site.xpath('.//a[@class="bi"]/@href').extract()[0] 
      item['team_stats_link'] = site.xpath(".//a[text()='Stats']/@href").extract()[0] 
      yield item 

它產生:

{'team_link': u'http://espn.go.com/nba/team/_/name/bos/boston-celtics', 'team_name': u'Boston Celtics', 'team_stats_link': u'/nba/teams/stats?team=bos'} 
{'team_link': u'http://espn.go.com/nba/team/_/name/bkn/brooklyn-nets', 'team_name': u'Brooklyn Nets', 'team_stats_link': u'/nba/teams/stats?team=bkn'} 
... 
+0

你介意解釋爲什麼你會選擇相對路徑?另外,爲什麼要通過'中等標識'類而不是'bi'類? – user1636797

+0

@ user1636797我仍然使用'bi'來查找團隊的名稱和鏈接。你需要把它做成相對的,這樣你才能在團隊內搜索而不是整個頁面。希望有所幫助。 – alecxe

+0

我明白你的意思了。謝謝! – user1636797

相關問題