python无法为<a>标记指定xpath

2024-03-29 12:52:47 发布

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

请看这张来自firebug的图片

enter image description here

我想把测试放在<a>标记中。我用了这个:

def parse(self, response):
    sel = Selector(response)
    sites = sel.xpath('//div[@class="item paid-featured-item"]/div[@class="listing-item"]')
    cars = []
    for site in sites:
        car = CarItem()
        car['ATitle']=xpath('.//div[@class="block item-title"]/h3/span[@class="title"]/a/text()').extract()
        cars.append(car)
    return cars

我想我使用了正确的xpath。但似乎没有,因为我得到的结果是空的。你知道吗

有什么帮助吗?你知道吗


Tags: 标记divtitleparseresponsedef图片item
1条回答
网友
1楼 · 发布于 2024-03-29 12:52:47

以下是OP的评论:

这可能就是你的目标:

def parse(self, response):
    sel = Selector(response)
    sites = sel.xpath('//div[@class="item paid-featured-item"]/div[@class="listing-item"]')
    cars = []
    for site in sites:
        car = CarItem()
        car['ATitle']=site.xpath('.//div[@class="block item-title"]/h3/span[@class="title"]/a/text()').extract()
        cars.append(car)
    return cars

或者,我看到您正在使用一个最新的Scrapy版本,所以您可能希望尝试CSS选择器,它通常使选择器表达式更易于阅读和维护。你知道吗

对你来说,你可以用

def parse(self, response):
    sel = Selector(response)
    sites = sel.css('div.paid-featured-item div.listing-item')
    cars = []
    for site in sites:
        car = CarItem()
        car['ATitle'] = site.css('div.item-title h3 span.title a::text').extract()
        cars.append(car)
    return cars

请注意,a::text语法是对CSS选择器的粗略扩展

相关问题 更多 >