2016-12-27 87 views
0

我已经开发了一个网址为this的web-crawler,刚刚出了问题。如何跳过一轮“for循环”,并在满足特定的“if”条件时继续下一轮?

我试图做的是抓取每个二手车库存数据列表,如果在每个数据的第四列有一个“图像”数据(粉红色图像表示“售罄”)在“价格“标签,我将跳过该列表并继续抓取下一个股票数据。

(我上面的意思是跳过整个下面的代码,并开始下一轮的“for循环”。“继续”跳过唯一的“如果”功能,并保持运行下面的代码。)

以下是我的代码

from bs4 import BeautifulSoup 
import urllib.request 

URL=http://www.bobaedream.co.kr/cyber/CyberCar.php?gubun=I&page=20 
res = urllib.request.urlopen(URL) 
html = res.read() 
soup = BeautifulSoup(html, 'html.parser') 
table = soup.find('table', class_='cyber') 

# 50 lists per each page 
links = [] 
for p in range(50): 

    #Car_Price 
    car_price=table.find_all('td', class_='price') 
    if car_price[p].find('em').text: 
     car_price_confirm = car_price[p].find('em').text 
    elif car_price[p].find('em').find('img'): 
     pass 

    carinfo = table.find_all('td', class_='carinfo') 
    carinfo_title = carinfo[p].find('a', class_='title').text 
    links.append(carinfo[p].find('a')['href']) 

    print(p+1, car_price_confirm, link[p]) 
+0

请您在收到答案后不要完全改变您的问题。如果需要,请提出另一个问题。 –

回答

4

您正在寻找continue。 它确实是你想要的。

一个例子,打印不运行的对。 继续跳到下一个迭代:

for i in range(5): 
    if i % 2 == 0: 
     continue 
    print(i) 

# Do not print evens 
1 
3 

This问题也可以有很大的帮助!

+0

感谢您的回复。但我的意思是跳过以下全部代码并开始下一轮“for循环”。 “continue”跳过唯一的“if”功能并继续运行下面的代码。 –

+0

感谢您的评论,我想我找到了跳过并重新启动“for循环”问题。但是我从代码中又遇到了另一个问题。你介意帮我解决这个问题吗? –

+0

你完全改变了这个问题,我认为这是不对的。至少你试图找出错误是什么? – Lucas

1

编辑:继续跳过整个迭代。它对if语句没有影响。检查你的代码。

Python中的continue语句将控件返回到while循环的开头。 continue语句拒绝循环当前迭代中的所有剩余语句,并将控件移回循环的顶部。

要跳过当前for循环的其余部分,请使用continue声明。

for p in range(50): 
    car_price=table.find_all('td', class_='price') 

    if car_price[p].find('em').find('img'): 
     continue 

    ... 
+0

感谢您的评论,我想我找到了跳过并重新启动“for循环”问题。但是我从代码中又遇到了另一个问题。你介意帮我解决这个问题吗? –

相关问题