【问题标题】:How am I getting two different results from same Python print command?如何从同一个 Python 打印命令获得两个不同的结果?
【发布时间】: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 &amp; 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() 会引发属性错误。循环结束。
  • 是的,如果我将exceptcontinue 替换为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


【解决方案1】:

你有一条毯子except:

try:
    # ...
except:
    continue

所以块中的任何错误都将被屏蔽,您的循环将被跳过。不要在没有再次抬起的情况下使用除处理程序之外的毯子,请参阅Why is "except: pass" a bad programming practice?。至少只捕获 Exceptionprint 那个错误:

except Exception as e:
    print 'Encountered:', e

如果没有正确的诊断,我们只能猜测。

当没有href 属性时,您肯定遇到的一个错误是属性错误; None 对象没有 startswith 属性:

if not tag.get('href', None).startswith('..'):

而不是None 返回一个空字符串:

if not tag.get('href', '').startswith('..'):

或者更好的是,只选择带有href 属性的a 标记:

tags = soup.select('a[href]')

【讨论】:

  • 非常有帮助。
猜你喜欢
  • 2014-09-02
  • 2019-08-27
  • 1970-01-01
  • 2016-08-29
  • 2013-10-28
  • 1970-01-01
  • 2020-11-21
  • 2019-12-18
  • 2021-11-13
相关资源
最近更新 更多