Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.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 收到xml解析的无响应后如何继续_Python_Xml_Beautifulsoup - Fatal编程技术网

Python 收到xml解析的无响应后如何继续

Python 收到xml解析的无响应后如何继续,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,我正在使用瓶鼻API和BeautifulSoup解析xml响应来查找Amazon产品的价格。 我有一个预定义的产品列表,代码可以遍历这些产品。 这是我的代码: 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.tx

我正在使用瓶鼻API和BeautifulSoup解析xml响应来查找Amazon产品的价格。 我有一个预定义的产品列表,代码可以遍历这些产品。 这是我的代码:

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
这很好用,会在我的亚马逊产品列表中运行,直到找到一个没有任何标签值的产品

Python将在哪个时间抛出此响应:

AttributeError: 'NoneType' object has no attribute 'Amount'
这很有意义,因为我搜索的BS没有找到标记/字符串。从我试图实现的目标来看,没有任何价值是完全正确的,但是代码在这一点上崩溃了,不会继续

我试过:

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

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

与无进行比较的正确方法是
是无,而不是
==None
不是无,不是
!=无

其次,您还需要勾选“无”,而不是“金额”,即:

if soup.LowestNewPrice is not None:
    ... read soup.LowestNewPrice.Amount

您可以使用异常处理:

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


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

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

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

print i , newprice, usedprice

这将起作用并允许代码继续。但是,代码将完全跳过整个循环,因此如果没有使用的价格,它也将跳过查找新价格。理想情况下,我想要的是,如果有一个“无”响应,则调用的值只需设置为等于零。有没有一种方法可以在例外情况下做到这一点?为了澄清,我刚刚尝试了这个
try:newprice=soup.LowestNewPrice.Amount.string,AttributeError:newprice=0除外continue
,但它将跳过整个for循环迭代,并移到列表中的下一项。@我在答案中添加了一个选项,以说明如何将值设置为零并继续。请注意,
continue
表达式意味着转到下一个循环索引,因此在本例中不希望使用它。有关异常处理的更多信息,请参阅。哦,很好,我从异常中删除了
continue
,现在它可以工作了。非常好,非常感谢。如果soup.LowestNewPrice.Amount不是None,则将行更改为:
:newprice=soup.LowestNewPrice.Amount
仍会引发非类型响应。