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))
这是使用 beautiful soup 来解析 HTML 并找到位置 3 处的链接(名字是 1)。请点击该链接。重复此过程 4 次。有没有比使用嵌套循环更有效的方法?
最佳答案
正如 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 个项目,则两种实现都不会出现任何问题,因为它们只会从层中返回。
关于python - 使用嵌套 if 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539170/