Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python索引器:列表索引超出范围-美化组_Python - Fatal编程技术网

python索引器:列表索引超出范围-美化组

python索引器:列表索引超出范围-美化组,python,Python,我写了一些代码,其中返回两个输出出现错误,我的代码的主要问题是什么 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import os import sys import unicodecsv as csv import codecs from urllib.request import urlopen for i in range(22): my_url = "htt

我写了一些代码,其中返回两个输出出现错误,我的代码的主要问题是什么

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import os
import sys
import unicodecsv as csv
import codecs
from urllib.request import urlopen


for i in range(22):

    my_url = "https://www.bamilo.com/electronic_accessories/?source=gfm/?facet_is_mpg_child=0&viewType=gridView&page="

    uClient = uReq(my_url + str(i))

    page_html = uClient.read()

    uClient.close()

    page_soup = soup(page_html, "html.parser")

    containers = page_soup.findAll("div" , {"class" : "sku -gallery" })

    filename = "product.csv"
    f = codecs.open(filename, "a" , "utf-8-sig")
    headers = "price_two\n"
    f.write(headers)


    for container in containers:

        price_old = container.findAll("span",{"class" : "price -old "} )

        price_two = price_old[0].text.strip()

        print("price_two " + price_two)

        f.write(price_two.replace(",", "")  + "\n")

f.close()
埃罗尔:::

> price_two 1,800,000ریال
price_two 2,800,000ریال
Traceback (most recent call last):
  File "F:\bam.py", line 34, in <module>
    price_two = price_old[0].text.strip()
IndexError: list index out of range
>两个180万欧元的价格
价格为2800000欧元
回溯(最近一次呼叫最后一次):
文件“F:\bam.py”,第34行,在
price\u two=price\u old[0]。text.strip()
索引器:列表索引超出范围

您的集装箱有时可能不会退回任何
'price-old'
项目。在这种情况下,
price\u old
是一个空列表,因此查找
price\u old[0]
失败。添加一个条件以检查此情况:

for container in containers:

    price_old = container.findAll("span",{"class" : "price -old "} )
    if len(price_old) > 0:
        price_two = price_old[0].text.strip()

        print("price_two " + price_two)

        f.write(price_two.replace(",", "")  + "\n")

欢迎来到SO!请使用,并尝试以易于阅读的方式设置问题的格式,如错误消息所示,
price\u old
有时没有第一个元素,即它可能是空的。您可能需要详细说明一下您在这里做了什么……添加条件以检查列表是否为空