[英]Why do I get endless loop when I insert 2 lines in Python?
while True:
print ("test")
sleep(3)
try:
doc = html.fromstring(page.content)
XPATH_NAME = '//h1[@id="title"]//text()'
XPATH_SALE_PRICE = '//span[contains(@id,"priceblock_ourprice") or contains(@id,"saleprice")]/text()'
XPATH_ORIGINAL_PRICE = '//td[contains(text(),"List Price") or contains(text(),"M.R.P") or contains(text(),"Price")]/following-sibling::td/text()'
XPATH_CATEGORY = '//a[@class="a-link-normal a-color-tertiary"]//text()'
XPATH_AVAILABILITY = '//div[@id="availability"]//text()'
RAW_NAME = doc.xpath(XPATH_NAME)
RAW_SALE_PRICE = doc.xpath(XPATH_SALE_PRICE)
RAW_CATEGORY = doc.xpath(XPATH_CATEGORY)
RAW_ORIGINAL_PRICE = doc.xpath(XPATH_ORIGINAL_PRICE)
RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY)
print(RAW_SALE_PRICE)
NAME = ' '.join(''.join(RAW_NAME).split()) if RAW_NAME else None
SALE_PRICE = ' '.join(''.join(RAW_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None
CATEGORY = ' > '.join([i.strip() for i in RAW_CATEGORY]) if RAW_CATEGORY else None
ORIGINAL_PRICE = ''.join(RAW_ORIGINAL_PRICE).strip() if RAW_ORIGINAL_PRICE else None
AVAILABILITY = ''.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None
print(SALE_PRICE)
if not ORIGINAL_PRICE:
ORIGINAL_PRICE = SALE_PRICE
data = {
'NAME': NAME,
'SALE_PRICE': SALE_PRICE,
'CATEGORY': CATEGORY,
'ORIGINAL_PRICE': ORIGINAL_PRICE,
'AVAILABILITY': AVAILABILITY,
'URL': url,
}
return data
except Exception as e:
print
e
This works perfectly fine. 这完全没问题。 But when I insert
但是当我插入
if SALE_PRICE.startswith('EUR'):
SALE_PRICE = SALE_PRICE.replace('EUR ', '')
after the Lins where I Strip the RAW Variables into the normal Variables (NAME,SALE_PRICE) then I will end in a infitine loop - why? 在Lins之后,我将RAW变量删除到正常变量(NAME,SALE_PRICE),然后我将以一个infitine循环结束 - 为什么?
See the line: 看到这一行:
SALE_PRICE = ' '.join(''.join(RAW_SALE_PRICE).split()).strip() if RAW_SALE_PRICE else None
here SALE_PRICE can be assigned a None
value. 这里SALE_PRICE可以分配一个
None
值。 When you add your lines you are in some cases attempting to do .startswith
on a None value. 添加
.startswith
,在某些情况下,尝试在None值上执行.startswith
。 That will lead to an exception. 这将导致例外。 In your exception clause you do not break the loop and it will continue forever.
在你的例外条款中,你不会破坏循环,它将永远持续下去。
Add a break
or return
to your exception clause. 添加
break
或return
您的exception子句。
Take try catch block outside of while loop, in other words while to be nested within try, something like this 在while循环之外尝试catch块,换句话说,在try中嵌套,就像这样
try:
while(true):
#All your code
except Exception as e:
print e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.