【发布时间】:2016-07-03 09:57:23
【问题描述】:
对于第一个print tag,我得到了一个包含数百个<a 标签的大列表。对于第二个print tag,我得到一个包含四个<a 标签的列表,不包括我想要的标签。
我想要的标签之一是在tags 的末尾。在打印完所有数百个标签后,我正在打印最后一个标签,即打印正确的结束标签。但是通过在同一个(未更改的)列表tags 上运行另一个 for 循环,我不仅得到了不同的结果,而且明显不同。
无论有没有 `print '\n\n\n' 都会出现这种现象,只是为了让我更容易看到两个打印件之间的分割。
这个列表在第一个和第二个for 循环之间发生了什么导致这个问题?
(此代码与我在脚本中的代码完全相同。最初我没有从第一个 for 循环到空行的行,并且这样做是为了调试缺少正确的 URL 从最终结果。)
编辑:此外,这里是所有 print 语句的打印内容(仅在 for 循环中的第一个 print 的最后一部分):
import urllib
from bs4 import BeautifulSoup
startingList = ['http://www.stowefamilylaw.co.uk/']
for url in startingList:
try:
html = urllib.urlopen(url)
soup = BeautifulSoup(html,'lxml')
tags = soup('a')
for tag in tags:
print tag
print tags[-1]
print '\n\n\n'
for tag in tags:
print tag
if not tag.get('href', None).startswith('..'):
continue
except:
continue
....
<a class="shiftnav-target" href="http://www.stowefamilylaw.co.uk/faq-category/decrees-orders-forms/" itemprop="url">Decrees, Orders & Forms</a>
<a class="shiftnav-target" href="http://www.stowefamilylaw.co.uk/faq-category/international-divorce/" itemprop="url">International Divorce</a>
<a class="shiftnav-target"><i class="fa fa-chevron-left"></i> Back</a>
<a class="shiftnav-target" href="http://www.stowefamilylaw.co.uk/contact/" itemprop="url"><i class="fa fa-phone"></i> Contact</a>
<a class="shiftnav-target" href="http://www.stowefamilylaw.co.uk/contact/" itemprop="url"><i class="fa fa-phone"></i> Contact</a>
<a href="http://www.stowefamilylaw.co.uk/">Stowe Family Law</a>
<a href="#spu-5086" style="color: #fff"><div class="callbackbutton"><i class="fa fa-phone" style="font-size: 16px"></i> Request Callback </div></a>
<a href="#spu-5084" style="color: #fff"><div class="callbackbutton"><i class="fa fa-envelope-o" style="font-size: 16px"></i> Quick Enquiry </div></a>
<a class="ubermenu-responsive-toggle ubermenu-responsive-toggle-main ubermenu-skin-black-white-2 ubermenu-loc-primary" data-ubermenu-target="ubermenu-main-3-primary"><i class="fa fa-bars"></i>Main Menu</a>
【问题讨论】:
-
现在用我能以最简单的方式准确显示问题的代码进行了编辑。让我知道是否还有其他需要调整/强调的地方。如果现在可以,请允许其他人也尝试帮助解决此问题。谢谢马丁
-
你有一条毯子
except。删除它或用打印错误的东西替换它。我敢打赌,当.get()返回None时,.startswith()会引发属性错误。循环结束。 -
是的,如果我将
except的continue替换为print "this is an error",它也会打印以前的所有内容以及错误消息。 -
我刚刚在 if 语句中添加了 try 和 except,这似乎解决了问题。感谢您的建议,以及从现在开始如何构建此类问题的说明
-
另见blog.codekills.net/2011/09/29/the-evils-of--except-- 通常
try块应尽可能短,except应尽可能具体。我认为将tag.get的第二个参数设为字符串会比用try包装一个简单的条件更简洁、更有效(它也将代码inside 包装在if,再次使块比理想时间长)。
标签: python