【问题标题】:Python - IndexError: list index out of range - not workingPython - IndexError:列表索引超出范围 - 不起作用
【发布时间】:2018-06-05 17:25:42
【问题描述】:

这是我的 scrap.py 代码

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

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

uClient = uReq(website)
page_html = uClient.read()
uClient.close()

soup_html = soup(page_html, "html.parser")
result_html = soup_html.findAll("p", {"class":"result-info"})

filename = "products.csv"

f = open(filename, "w", encoding='utf8')
headers = "car_name, price\n"
f.write(headers)

for container in result_html:   
    carname = container.a.text

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

    f.write(carname + "," + price + "\n")

f.close()

在终端上,它工作正常,但是当我循环它时,它会给出以下错误..

Traceback (most recent call last):
  File "scrap.py", line 23, in <module>
    price = price_container[0].text.splitlines()
IndexError: list index out of range

请帮忙。谢谢

【问题讨论】:

  • 我投票决定将此问题作为离题结束,因为 OP 希望找到人来编写他的任务并在每个答案时提出后续问题

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

这是因为有些汽车没有价格,例如this one。如果没有价格,您可以将价格发送到unknown

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

或者你可以跳过那些没有价格的,这样它们就不会被写入文件:

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

如何按价格排序?

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()

【讨论】:

  • 太棒了。谢谢
  • 如何按价格对结果进行排序?
  • @ShahidShabbir:我添加了这一部分。但是请现在停下来,因为您只是在要求两个人同时为您工作..
  • 我们如何获取页面上每个项目内的联系电话和电子邮件地址?
  • 正如我所说:其余的请你自己做,不要让这里的人为你工作。如果你想让人们为你编程,你通常需要付钱给他们,对吧?
【解决方案2】:

试试下面的。它将获取所有商品和价格并处理IndexError(如果有)。

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)

我尝试缩短您的代码以使其看起来更好。

【讨论】:

  • 它是你的缩写,但对我来说非常复杂,因为我是 Python 新手
  • 如何按价格对结果进行排序?
  • 将此行替换为现有的print 语句print("Car_Name: {}\nPrice: {}\n".format(carname,price))
猜你喜欢
  • 2016-08-25
  • 2017-04-05
  • 2012-07-15
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多