2017-01-08 75 views
2
for tag in tags: 
    Ulist1.append(tag.get('href', None)) 

if len(Ulist1) > 2: 
    print Ulist1[2] 
    html = urllib.urlopen(Ulist1[2]).read() 
    soup = BeautifulSoup(html) 
    tags = soup('a') 
    Ulist2 = list() 

    for tag in tags: 
     Ulist2.append(tag.get('href', None)) 

    if len(Ulist2) > 2: 
     print Ulist2[2] 
     html = urllib.urlopen(Ulist2[2]).read() 
     soup = BeautifulSoup(html) 
     tags = soup('a') 
     Ulist3 = list() 

     for tag in tags: 
      Ulist3.append(tag.get('href', None)) 

     if len(Ulist3) > 2: 
      print Ulist3[2] 
      html = urllib.urlopen(Ulist3[2]).read() 
      soup = BeautifulSoup(html) 
      tags = soup('a') 
      Ulist4 = list() 

      for tag in tags: 
       Ulist4.append(tag.get('href', None)) 

這是使用美麗的湯解析HTML並找到位置3(名字是1)的鏈接。關注該鏈接。重複這個過程4次。有沒有更有效的方式來做到這一點,而不是使用嵌套循環?使用嵌套ifs的替代方法

+5

如果你有**工作代碼**,你認爲可以改進,參見[codereview.se] – jonrsharpe

+1

如果複製和粘貼代碼,然後進行細微的變化,你應該因子它變成一個功能,並通在差異作爲參數。 –

回答

2

你可以像Peter Wood說的那樣將它分解成一個函數。這是一個可能的實現,它顯示了基本概念。

def print_third_recursive(tags, iterations): 
    Ulist = [tag.get('href', None) for tag in tags] # more pythonic 
    if len(Ulist) > 2 && iterations : 
     print Ulist[2] 
     html = urllib.urlopen(Ulist[2]).read() 
     soup = BeautifulSoup(html) 
     new_tags = soup('a') 
     use_third(new_tags, iterations - 1) 

use_third_recursive(tags, 3) 

如果您希望函數更簡單,那麼無需使用遞歸也可以完成此操作。

def print_third(tags): 
    Ulist = [tag.get('href', None) for tag in tags] # more pythonic 
    new_tags = [] 
    if len(Ulist) > 2: 
     print Ulist[2] 
     html = urllib.urlopen(Ulist[2]).read() 
     soup = BeautifulSoup(html) 
     new_tags = soup('a') 
    return new_tags 

print_third(
    print_third(
     print_third(tags) 
    ) 
) 

也不應該實行有任何問題,如果沒有在標籤列表,因爲他們只會回到右後衛出了塗層的一個3項。

0

正如彼得和安東尼所說,你可以提取方法並使事情更簡單。

但是,在一般經驗法則,而不是嵌套IFS,您可以更改條件的補充和回報。

在你的榜樣

if len(Ulist1) > 2: do_stuff() if len(Ulist1) > 2: do_more_stuff()

代替如下,你可以寫:

if len(Ulist1) < 2: # the compement of the original condition return do_stuff() if len(Ulist1) < 2: # the compement of the original condition return do_more_stuff()

所以,你可以編寫代碼如下:

if len(Ulist1) < 2: 
    return 

print Ulist1[2] 
html = urllib.urlopen(Ulist1[2]).read() 
soup = BeautifulSoup(html) 
tags = soup('a') 
Ulist2 = list() 

for tag in tags: 
    Ulist2.append(tag.get('href', None)) 

if len(Ulist2) < 2: 
    return 

print Ulist2[2] 
html = urllib.urlopen(Ulist2[2]).read() 
soup = BeautifulSoup(html) 
tags = soup('a') 
Ulist3 = list() 

for tag in tags: 
    Ulist3.append(tag.get('href', None)) 

if len(Ulist3) < 2: 
    return 

print Ulist3[2] 
html = urllib.urlopen(Ulist3[2]).read() 
soup = BeautifulSoup(html) 
tags = soup('a') 
Ulist4 = list() 

for tag in tags: 
    Ulist4.append(tag.get('href', None)) 

當然,我建議你像安東尼在上面寫的那樣提取方法。

希望它有幫助。