我在使用此代码时遇到问题,因为除了将输出写入“ 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')


Python抛出ValueError,因为您不能添加intstr。您还会发现所有不明智的异常。更改有问题的行以将authority转换为str

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


而且你应该没事。摆脱通用的except子句,仅捕获要捕获的特定异常。在开发此代码时,我建议您不要捕获任何异常,只是为了告诉您出问题的原因。

09-07 23:47