gpt4 book ai didi

python - 收到 xml 解析的 None 响应后如何继续

转载 作者:行者123 更新时间:2023-12-01 04:08:35 24 4
gpt4 key购买 nike

我正在使用 Bottlenose 的 API 查找亚马逊产品的价格,并使用 BeautifulSoup 解析 xml 响应。我有一个代码迭代的预定义产品列表。这是我的代码:

import bottlenose as BN
import lxml
from bs4 import BeautifulSoup

i = 0
amazon = BN.Amazon('myid','mysecretkey','myassoctag',Region='UK',MaxQPS=0.9)
list = open('list.txt', 'r')

print "Number", "New Price:","Used Price:"

for line in list:
i = i + 1
listclean = line.strip()
response = amazon.ItemLookup(ItemId=listclean, ResponseGroup="Large")

soup = BeautifulSoup(response, "xml")

usedprice=soup.LowestUsedPrice.Amount.string
newprice=soup.LowestNewPrice.Amount.string
print i , newprice, usedprice

这工作正常,并将遍历我的亚马逊产品列表,直到找到对该组标签没有任何值(value)的产品,like no new/used price.

Python 将抛出此响应:

AttributeError: 'NoneType' object has no attribute 'Amount'

这是有道理的,因为我搜索的 BS 没有找到标签/字符串。从我想要实现的目标来看,没有任何值(value)是完全可以的,但是代码此时崩溃并且不会继续。

我已经尝试过:

if soup.LowestNewPrice.Amount != None:
newprice=soup.LowestNewPrice.Amount.string
else:
continue

还尝试过:

newprice=0
if soup.LowestNewPrice.Amount != 0:
newprice=soup.LowestNewPrice.Amount.string
else:
continue

收到非类型值返回后,我不知道如何继续。不确定问题是否根本在于我正在使用的语言或库。

最佳答案

您可以使用异常处理:

try:
# operation which causes AttributeError
except AttributeError:
continue

将执行 try block 中的代码,如果引发 AttributeError,执行将立即进入 except block (这将导致运行循环中的下一项)。如果没有引发错误,代码将愉快地跳过 except block 。

<小时/>

如果您只想将缺失值设置为零并打印,您可以这样做

try: newprice=soup.LowestNewPrice.Amount.string
except AttributeError: newprice=0

try: usedprice=soup.LowestUsedPrice.Amount.string
except AttributeError: usedprice=0

print i , newprice, usedprice

关于python - 收到 xml 解析的 None 响应后如何继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com