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))
这是使用BeautifulSoup解析HTML并在位置3(名字是1)找到链接。遵循这个链接。重复这个过程4次。有没有比使用嵌套循环更有效的方法?你知道吗
正如Peter和Anthony所说,您可以提取方法并使事情变得更简单。你知道吗
但是,一般来说,使用拇指规则,而不是嵌套的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()
因此,您的代码可以编写如下:
当然,我建议你提取安东尼在上面写的方法。你知道吗
希望有帮助。你知道吗
你可以像彼得·伍德说的那样把它分解成一个函数。下面是一个可能的实现,它展示了基本概念。你知道吗
如果您希望函数更简单,也可以不使用递归来完成。你知道吗
如果其中一个标记列表中没有3个项,那么这两个实现都不应该有任何问题,因为它们将直接从层中返回。你知道吗
相关问题 更多 >
编程相关推荐