Will W Will W - 7 months ago 18
Python Question

How to do if else statement in python

I am a python/scrapy newbie. I am trying to scrape a website for practice and basically when data-src exists, then I want to use the value from img::attr(data-src),

def parse(self, response):

for item in items:

listing['img'] = item.css('div img::attr(data-src)').extract()


otherwise if data-src does not exist then use img::attr(src)

listing['img'] = item.css('div img::attr(src)').extract()


But the question is how to do it in an if statement?

listing['img'] = if item.css('div img::attr(data-src)'): item.css('div img::attr(data-src)').extract() else: item.css('div img::attr(src)').extract()


Of course this does not work and it has an error:

SyntaxError: invalid syntax


Thanks for your help and input!

Answer

Maybe this:

for item in items:
    if item.css('div img::attr(data-src)'): 
        listing['img'] = item.css('div img::attr(data-src)').extract() 

    else:
        listing['img'] = item.css('div img::attr(src)').extract()