我需要从给定 anchor 标记的特定文本的 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
这是我遇到问题的行:
item['team_stats_link'] = site.xpath('//a[text()='Stats']/@href').extract()
我也尝试过:
item['team_stats_link'] = site.xpath('//a[contains(text(), 'Stats')]/@href).extract()
最佳答案
循环内的 xpath 应以 .//
开头,换句话说,您需要使其相对于 site
。
我还会使用 medium-logos
类遍历 ul
内的 li
标签,而不是搜索第一个 div
在 div
内的第三个 div
内,content
id:
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'}
...
关于python - 使用 Xpath 提取给定 anchor 标记文本的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23692526/