J
J
JRazor2015-03-17 06:35:26
Python
JRazor, 2015-03-17 06:35:26

Scrapy: how after response.xpath to get one element and not a list?

Hello fellow toasters.
I am already writing a script on Scrapy and a question arose that I could not solve myself: suppose there is such a code -

def parse_item(self, response):
        sel = Selector(response)
        image = sel.xpath('//*[@id="listing-images"]/div/a/@href').extract()[0]
        name =  sel.xpath('//*[@id="main"]/div/h1/text()').extract()[0]

sel.xpath ('').extract() returns a list. Of course, you have to either join , or through [0] turn the list into one element. But a number of problems are connected with this: join'y to prescribe every time is nonsense, and [0] can return an error after an empty list.
Actually a question - whether there is an alternative to extract'u? How to return one element after xpath?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
Hu New, 2015-03-17
@stopbreath

first_or_none = lambda x: x[0] if x else None
Here's a little lambda function that returns the first element of a sequence, or None.

L
lololololo, 2015-03-18
@lololololo

How to return one element after xpath?

How to return one element if there are 0 of them?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question