Python - IndexError: list index out of range - not working

后端 未结 2 1904
春和景丽
春和景丽 2021-01-29 10:15

This is my scrap.py code

from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq

website = \"https://houston.craigslist.org/search/cta\         


        
2条回答
  •  情深已故
    2021-01-29 10:37

    This is because some cars just have no price, e.g. this one. You can put price to unknown if there was no price:

    price_container = container.findAll('span', {'class':'result-price'})
    if len(price_container) > 0:
        price = price_container[0].text
    else:
        price = 'unknown'
    

    Or you could just skip the ones without price so they'll not get written to the file:

    price_container = container.findAll('span', {'class':'result-price'})
    if len(price_container) == 0:
       continue
    price = price_container[0].text
    

    How can I sort it by price?

    results = []
    for container in result_html:   
        carname = container.a.text
    
        price_container = container.findAll('span', {'class':'result-price'})
        if len(price_container) == 0:
            continue
    
        price = price_container[0].text.strip('$')
        results.append((int(price), carname))
    
    for price, carname in sorted(results):
        f.write("{}, {}\n".format(carname, price))
    
    f.close()
    

提交回复
热议问题