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

后端 未结 2 1802
春和景丽
春和景丽 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:38

    Try the below one. It will fetch you all the items and price and handle IndexError if there is any.

    from bs4 import BeautifulSoup
    from urllib.request import urlopen
    
    response = urlopen("https://houston.craigslist.org/search/cta")
    soup_html = BeautifulSoup(response.read(), "html.parser")
    for container in soup_html.find_all("p", {"class":"result-info"}):   
        carname = container.find_all("a")[0].text
        try:
            price = container.find_all('span', {'class':'result-price'})[0].text
        except IndexError:
            price = ""
        print(carname,price)
    

    I tried to shorten your code to make it look better.

提交回复
热议问题