获取TypeError:“NoneType”对象在Web报废中不可订阅

2024-04-19 01:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图分析一个网站,并保存其内容到CSV文件,但在线

brand = make_rating_sp[0].img["title"].title()

我发现打字错误了

for container in containers:
   make_rating_sp = container.div.select("a")

   brand = make_rating_sp[0].img["title"].title()

   product_name = container.div.select("a")[2].text

   shipping = container.findAll("li", {"class": "price-ship"})[0].text.strip().replace("$", 
   "").replace(" Shipping", "")
   print("brand: " + brand + "\n")
   print("product_name: " + product_name + "\n")
   print("shipping: " + shipping + "\n")
   f.write(brand + ", " + product_name.replace(",", "|") + ", " + shipping + "\n")

Tags: textnamedivimgmaketitlecontainerproduct
1条回答
网友
1楼 · 发布于 2024-04-19 01:46:07

您很可能看到IndexError: list index out of range,但如果make_rating_sp列表包含元素,但指定索引处的特定a标记不包含img标记,则也可能会遇到问题。你知道吗

尝试添加以下内容:

   brand = ""
   try:
       brand = make_rating_sp[0].img["title"].title()
   except:
       pass

通常在Python中,您需要捕获特定的exceptions,但在本例中,一个通用的解决方案可能就足够了。你知道吗

相关问题 更多 >