I've written a script to parse the name and price of certain items from craigslist. The xpath I've defined within my scraper are working ones. The thing is when I try to scrape the items in usual way then applying try/except block I can avoid IndexError when the value of certain price is none. I even tried with customized function to make it work and found success as well.
However, In this below snippet I would like to apply lambda function to kick out IndexError error. I tried but could not succeed.
Btw, when I run the code It neither fetches anything nor throws any error either.
import requests
from lxml.html import fromstring
page = requests.get('http://bangalore.craigslist.co.in/search/rea?s=120').text
tree = fromstring(page)
# I wish to fix this function to make a go
get_val = lambda item,path:item.text if item.xpath(path) else ""
for item in tree.xpath('//li[@class="result-row"]'):
link = get_val(item,'.//a[contains(@class,"hdrlnk")]')
price = get_val(item,'.//span[@class="result-price"]')
print(link,price)
lambdaexpression to define a named function; just use adefstatement.