过去几天,我一直在终端中运行以下脚本。我没有对其进行任何更改。以前,它一直运行良好,现在出现错误:
Traceback (most recent call last):
File "GetAlexRanking.py", line 193, in <module>
print("%s:%d" % (p.__class__.__name__, p.get_rank(url
TypeError: %d format: a number is required, not NoneType
这是完整的代码。应该可以将它保存在 .py 文件中,使用命令 python filename.py www.google.com 从终端 shell 运行它以打印出 Google 的一些流量统计信息。但是,这将不再对我有用。这里有什么问题?
import struct
import sys
import urllib
import urllib2
import httplib
import re
import xml.etree.ElementTree
class RankProvider(object):
"""Abstract class for obtaining the page rank (popularity)
from a provider such as Google or Alexa.
"""
def __init__(self, host, proxy=None, timeout=30):
"""Keyword arguments:
host -- toolbar host address
proxy -- address of proxy server. Default: None
timeout -- how long to wait for a response from the server.
Default: 30 (seconds)
"""
self._opener = urllib2.build_opener()
if proxy:
self._opener.add_handler(urllib2.ProxyHandler({"http": proxy}))
self._host = host
self._timeout = timeout
def get_rank(self, url):
"""Get the page rank for the specified URL
Keyword arguments:
url -- get page rank for url
"""
raise NotImplementedError("You must override get_rank()")
class AlexaTrafficRank(RankProvider):
""" Get the Alexa Traffic Rank for a URL
"""
def __init__(self, host="xml.alexa.com", proxy=None, timeout=30):
"""Keyword arguments:
host -- toolbar host address: Default: joolbarqueries.google.com
proxy -- address of proxy server (if required). Default: None
timeout -- how long to wait for a response from the server.
Default: 30 (seconds)
"""
super(AlexaTrafficRank, self).__init__(host, proxy, timeout)
def get_rank(self, url):
"""Get the page rank for the specified URL
Keyword arguments:
url -- get page rank for url
"""
query = "http://%s/data?%s" % (self._host, urllib.urlencode((
("cli", 10),
("dat", "nsa"),
("ver", "quirk-searchstatus"),
("uid", "20120730094100"),
("userip", "192.168.0.1"),
("url", url))))
response = self._opener.open(query, timeout=self._timeout)
if response.getcode() == httplib.OK:
data = response.read()
element = xml.etree.ElementTree.fromstring(data)
for e in element.iterfind("SD"):
popularity = e.find("POPULARITY")
if popularity is not None:
return int(popularity.get("TEXT"))
class GooglePageRank(RankProvider):
""" Get the google page rank figure using the toolbar API.
Credits to the author of the WWW::Google::PageRank CPAN package
as I ported that code to Python.
"""
def __init__(self, host="toolbarqueries.google.com", proxy=None, timeout=30):
"""Keyword arguments:
host -- toolbar host address: Default: toolbarqueries.google.com
proxy -- address of proxy server (if required). Default: None
timeout -- how long to wait for a response from the server.
Default: 30 (seconds)
"""
super(GooglePageRank, self).__init__(host, proxy, timeout)
self._opener.addheaders = [("User-agent", "Mozilla/4.0 (compatible; \
GoogleToolbar 2.0.111-big; Windows XP 5.1)")]
def get_rank(self, url):
# calculate the hash which is required as part of the get
# request sent to the toolbarqueries url.
ch = '6' + str(self._compute_ch_new("info:%s" % (url)))
query = "http://%s/tbr?%s" % (self._host, urllib.urlencode((
("client", "navclient-auto"),
("ch", ch),
("ie", "UTF-8"),
("oe", "UTF-8"),
("features", "Rank"),
("q", "info:%s" % (url)))))
response = self._opener.open(query, timeout=self._timeout)
if response.getcode() == httplib.OK:
data = response.read()
match = re.match("Rank_\d+:\d+:(\d+)", data)
if match:
rank = match.group(1)
return int(rank)
@classmethod
def _compute_ch_new(cls, url):
ch = cls._compute_ch(url)
ch = ((ch % 0x0d) & 7) | ((ch / 7) << 2);
return cls._compute_ch(struct.pack("<20L", *(cls._wsub(ch, i * 9) for i in range(20))))
@classmethod
def _compute_ch(cls, url):
url = struct.unpack("%dB" % (len(url)), url)
a = 0x9e3779b9
b = 0x9e3779b9
c = 0xe6359a60
k = 0
length = len(url)
while length >= 12:
a = cls._wadd(a, url[k+0] | (url[k+1] << 8) | (url[k+2] << 16) | (url[k+3] << 24));
b = cls._wadd(b, url[k+4] | (url[k+5] << 8) | (url[k+6] << 16) | (url[k+7] << 24));
c = cls._wadd(c, url[k+8] | (url[k+9] << 8) | (url[k+10] << 16) | (url[k+11] << 24));
a, b, c = cls._mix(a, b, c)
k += 12
length -= 12
c = cls._wadd(c, len(url));
if length > 10: c = cls._wadd(c, url[k+10] << 24)
if length > 9: c = cls._wadd(c, url[k+9] << 16)
if length > 8: c = cls._wadd(c, url[k+8] << 8)
if length > 7: b = cls._wadd(b, url[k+7] << 24)
if length > 6: b = cls._wadd(b, url[k+6] << 16)
if length > 5: b = cls._wadd(b, url[k+5] << 8)
if length > 4: b = cls._wadd(b, url[k+4])
if length > 3: a = cls._wadd(a, url[k+3] << 24)
if length > 2: a = cls._wadd(a, url[k+2] << 16)
if length > 1: a = cls._wadd(a, url[k+1] << 8)
if length > 0: a = cls._wadd(a, url[k])
a, b, c = cls._mix(a, b, c);
# integer is always positive
return c
@classmethod
def _mix(cls, a, b, c):
a = cls._wsub(a, b); a = cls._wsub(a, c); a ^= c >> 13;
b = cls._wsub(b, c); b = cls._wsub(b, a); b ^= (a << 8) % 4294967296;
c = cls._wsub(c, a); c = cls._wsub(c, b); c ^= b >>13;
a = cls._wsub(a, b); a = cls._wsub(a, c); a ^= c >> 12;
b = cls._wsub(b, c); b = cls._wsub(b, a); b ^= (a << 16) % 4294967296;
c = cls._wsub(c, a); c = cls._wsub(c, b); c ^= b >> 5;
a = cls._wsub(a, b); a = cls._wsub(a, c); a ^= c >> 3;
b = cls._wsub(b, c); b = cls._wsub(b, a); b ^= (a << 10) % 4294967296;
c = cls._wsub(c, a); c = cls._wsub(c, b); c ^= b >> 15;
return a, b, c
@staticmethod
def _wadd(a, b):
return (a + b) % 4294967296
@staticmethod
def _wsub(a, b):
return (a - b) % 4294967296
if __name__ == "__main__":
url = sys.argv[1]
providers = (AlexaTrafficRank(), GooglePageRank(),)
print("Traffic stats for: %s" % (url))
for p in providers:
print("%s:%d" % (p.__class__.__name__, p.get_rank(url)))
最佳答案
在您的两个 get_rank 实例方法中,您都有一行:
if response.getcode() == httplib.OK:
然后是另一个函数特定的 if。如果两者都评估为 True,这些方法只会返回一个值(另外,在 AlexaTrafficRank 中,element.iterfind("SD") 必须有值);否则,它们将隐式返回 None,因此会出现您看到的错误。
关于Python 正在工作 - 没有做任何更改 - 将不再工作。可能发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970166/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返