使用Xpath提取锚点标签文本中的href

2024-04-28 23:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从给定锚标记的特定文本的href属性中提取url。在

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

这是我遇到麻烦的线路:

^{pr2}$

我还试图:

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

有问题的网站:http://espn.go.com/nba/teams


Tags: textfromimportcomlinksiteextractitems
1条回答
网友
1楼 · 发布于 2024-04-28 23:45:26

循环中的xpath应该以.//开头,换句话说,需要使其相对于site。在

我还使用medium-logos类遍历ul内的li标记,而不是使用contentdiv中搜索第三个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

它产生:

^{pr2}$

相关问题 更多 >