2016-08-16 78 views
0

目的是打開頁面獲取網址18號,交換URL位置18和重新運行7次,但我的代碼卡住後獲得位置18,爲什麼ELIF不在24行? (無回溯,程序只是坐在那裏)elif語句沒有運行?

import urllib 
from BeautifulSoup import * 

#not the real url 
url= ('http://abc.googl.com') 
count=7 
position = 0 

#n will be used to check that the code i running 
n=0 

while count >= 0: 
    html = urllib.urlopen(url).read() 
    soup = BeautifulSoup(html) 

    tags = soup('a') 
    for tag in tags: 
     x= tag.get('href', None) 
     position=position+1 
     if position <= 18: 
      n=n+1 
      print 'calculating', n 
      print x 
     elif position == 18: 
      url=(x) 
      print 'new url', x 
      count=count-1 
      print 'new count', count 
      position=0 


if count == 0: 
    print "done" 
    print x 
+0

改變了if的值,現在唯一的問題是,它達不到計數0時不會停止。我會想出來:)謝謝大家的答案,非常有幫助! – Schwarz

+1

請不要編輯您的問題的解決方案。相反,您可以將*答案中的一個*標記爲「已接受」,以表明您找到了最有用的答案(並且不標記答案也很好)。請參閱[如何接受答案的工作?](https://meta.stackexchange.com/q/5234)瞭解更多信息。 –

回答

2
if position <= 18: 
    ... 
elif position == 18: 
    ... 

無論是ifelif分行,正趕上position如果position == 18(注意在if聲明<=),所以elif分支將永遠不會執行。

2

if排除elif條件:

if position <= 18: 

此相匹配,如果position == 18。當ifelif分支已匹配時,Python會忽略所有以下elif條件。

如果你想爲== 18情況下運行額外代碼,使用新if聲明:

if position <= 18: 
    # will run for all values of `position up to and including 18 

if position == 18: 
    # will *also* be run for the `position == 18` case 

另外,修復你的條件不重疊:

if position < 18: 
    # ... 
elif position == 18: 
    # runs only when position is exactly equal to 18 

if position <= 18: 
    # ... 
else: 
    # runs when the first condition no longer matches, so position > 18 
3

Ch安格

if position <= 8: 

通過

if position < 8: 

,並留下您elif相同。

通過具有條件<=8代碼總是進入,如果(當position<=8),但9(>8)時,它會進入elif。因此,如果您希望代碼在position = 8時輸入elif語句,則position = 8if不會爲真。

+1

@Schwarz如果有人給你正確的答案,你應該標記這樣的迴應 –