【问题标题】:Why this code is not writing anything in the text file?为什么这段代码没有在文本文件中写入任何内容?
【发布时间】:2014-04-08 00:17:57
【问题描述】:

我在使用此代码时遇到问题,因为除了将输出写入“f 文件”之外,它一切正常。谁能帮我解决这个问题?

问题出在这行:f.write(blog +' '+ authority +'\n')

        try:
            response = br.open(buyer)
            tree = html.fromstring(response.read())
            blogs = tree.xpath('//div/ul/li[@class="sidebar-item"]/a/@href')
            for blog in blogs:
                if '.blogspot.com' in blog:
                    try:
                        response = br.open(blog)
                    except HTTPError, e:

                        if 'http://www.blogger.com/create-blog.g?defaultSubdomain=' in e.read():
                            try:
                                response = br.open( 'http://www.opensiteexplorer.org/links?site=' + blog )
                            except Exception:
                                response = br.open( 'http://www.opensiteexplorer.org/links?site=' + blog )
                            tree = html.fromstring(response.read())
                            authority = int (tree.xpath('//span[@class="metrics-authority"]/text()')[1].strip())
                            if authority>1:
                                print blog
                                print 'This blog is ready to be registered'
                                print authority
                                f.write(blog +' '+ authority +'\n')
                        else:
                            print ''
        except Exception:
            print ''
print 'Finished'
f.close()

【问题讨论】:

  • 是报错还是不写?
  • 只是没有写任何东西,而在终端中,我可以看到输出
  • 您应该在f.write(blog + ' ' + authority + '\n') 中获得一个ValueError,因为authority 是一个int,您不能将其添加到@987654326 @。它要么没有进入那个分支,要么你在这里发布了一个错字,或者它抛出了一个异常。

标签: python urllib2 lxml mechanize


【解决方案1】:

问题来了:

当你尝试做的时候

f.write(blog +' '+ authority +'\n')

Python 正在抛出 ValueError,因为您无法添加 intstr。您还捕获了每一个不明智的异常。将违规行更改为将authority 转换为str

f.write(blog +' '+ authority +'\n')

你应该没事的。摆脱笼统的except 子句,只捕获您想要捕获的特定异常。在您开发此代码时,我建议您不要捕获任何异常,以便您知道为什么会出错。

【讨论】:

  • 我是 Python 的新手,请问您能解释一下使用什么来代替 try-except 结构吗?
  • @alexgarciab try 没问题,但你正在捕捉 Exception,这意味着一切。如果您想捕获特定的异常(例如,TypeErrorValueError),则应将其替换。这样您就不会意外地遇到您想以不同方式处理的错误。
猜你喜欢
  • 1970-01-01
  • 2021-01-09
  • 2017-07-13
  • 2013-10-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多