Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以通过Python获取页面排名和其他信息?_Python_Python 2.7_Seo_Pagerank_Alexa - Fatal编程技术网

是否可以通过Python获取页面排名和其他信息?

是否可以通过Python获取页面排名和其他信息?,python,python-2.7,seo,pagerank,alexa,Python,Python 2.7,Seo,Pagerank,Alexa,这个问题以前曾在这里被问过,但不幸的是,随着谷歌如此定期地更新其页面排名系统,没有一个答案经得起时间的考验。目前我无法找到任何有效的解决方案 我的目标是用Python编写一个简单的脚本,在给定域的情况下,获取该域的页面排名。我还想做的是编写一个函数来检索页面历史排名——那么www.example.com在2011年1月1日会有什么排名呢 有人知道这是否可能以及如何做到吗 我在pastebin上发现了一些遗留代码,但不幸的是,它给了我一个编译错误: import struct import sys

这个问题以前曾在这里被问过,但不幸的是,随着谷歌如此定期地更新其页面排名系统,没有一个答案经得起时间的考验。目前我无法找到任何有效的解决方案

我的目标是用Python编写一个简单的脚本,在给定域的情况下,获取该域的页面排名。我还想做的是编写一个函数来检索页面历史排名——那么www.example.com在2011年1月1日会有什么排名呢

有人知道这是否可能以及如何做到吗

我在pastebin上发现了一些遗留代码,但不幸的是,它给了我一个编译错误:

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 = "http://www.archlinux.org"
    providers = (AlexaTrafficRank(), GooglePageRank(),)

    print("Traffic stats for: %s" % (url))
    for p in providers:
        print("%s:%d" % (p.__class__.__name__, p.get_rank(url)))
导入结构
导入系统
导入URL库
导入urllib2
导入httplib
进口稀土
导入xml.etree.ElementTree
类RankProvider(对象):
“”“用于获取页面排名(流行度)的抽象类”
来自谷歌或Alexa等提供商。
"""
def _uinit _;(self,host,proxy=None,timeout=30):
“”“关键字参数:
主机--工具栏主机地址
proxy--代理服务器的地址。默认值:无
超时——等待服务器响应的时间。
默认值:30(秒)
"""
self.\u opener=urllib2.build\u opener()
如果代理:
self._opener.add_处理程序(urllib2.ProxyHandler({“http”:proxy}))
self.\u host=主机
self.\u timeout=超时
def get_排名(自我、url):
“”“获取指定URL的页面排名
关键字参数:
url—获取url的页面排名
"""
raise NOTEImplementedError(“必须重写get_rank()”)
等级AlexafficRank(RankProvider):
“”“获取URL的Alexa流量排名
"""
def uuu init uuuu(self,host=“xml.alexa.com”,proxy=None,timeout=30):
“”“关键字参数:
主机--工具栏主机地址:默认值:joolbarquerys.google.com
proxy--代理服务器的地址(如果需要)。默认值:无
超时——等待服务器响应的时间。
默认值:30(秒)
"""
超级(AlexaTrafficRank,self)。\uuuuu初始化(主机、代理、超时)
def get_排名(自我、url):
“”“获取指定URL的页面排名
关键字参数:
url—获取url的页面排名
"""
query=“http://%s/数据?%s”%(self.\u主机,urllib.urlencode((
(“cli”,10),
(“dat”、“nsa”),
(“ver”,“quirk searchstatus”),
(“uid”,“2012073094100”),
(“用户IP”,“192.168.0.1”),
(“url”,url)))
response=self.\u opener.open(查询,超时=self.\u超时)
如果response.getcode()==httplib.OK:
data=response.read()
element=xml.etree.ElementTree.fromstring(数据)
对于元素中的e.iterfind(“SD”):
流行度=e.find(“流行度”)
如果受欢迎程度不是零:
return int(popularity.get(“TEXT”))
GooglePageRank类(RankProvider):
“”“使用工具栏API获取google页面排名图。
归功于WWW::Google::PageRank CPAN包的作者
当我将代码移植到Python时。
"""
def uuu init uuuu(self,host=“toolbarquerys.google.com”,proxy=None,timeout=30):
“”“关键字参数:
主机--工具栏主机地址:默认值:toolbarquerys.google.com
proxy--代理服务器的地址(如果需要)。默认值:无
超时——等待服务器响应的时间。
默认值:30(秒)
"""
超级(GooglePageRank,self)。\uuuu初始化(主机、代理、超时)
self._opener.addheaders=[(“用户代理”,“Mozilla/4.0”(兼容\
谷歌工具栏2.0.111-big;Windows XP 5.1)“)]
def get_排名(自我、url):
#计算作为get的一部分所需的哈希
#发送到工具栏查询url的请求。
ch='6'+str(自计算新(“信息:%s”%(url)))
query=“http://%s/tbr?%s”%(self.\u主机,urllib.urlencode((
(“客户机”、“导航客户机自动”),
(“ch”,ch),
(“ie”、“UTF-8”),
(“oe”、“UTF-8”),
(“特征”、“等级”),
(“q”,“信息:%s%”(url(()())))
response=self.\u opener.open(查询,超时=self.\u超时)
如果response.getcode()==httplib.OK:
data=response.read()
match=re.match(“Rank\d+:\d+:(\d+),数据)
如果匹配:
等级=匹配。组(1)
返回整数(秩)
@类方法
def_compute_ch_new(cls,url):
ch=cls.\u compute\u ch(url)
ch=((ch%0x0d)和7)|((ch/7)=12:
a=cls._wadd(a,url[k+0]|(url[k+1]>3;
b=cls.\uWSUB(b,c);b=cls.\uWSUB(b,a);b^=(a>15;
返回a、b、c
@静力学方法
def_wadd(a、b):
返回(a+b)%4294967296
@静力学方法
定义(a,b):
返回(a-b)%4294967296
如果名称=“\uuuuu main\uuuuuuuu”:
url=”http://www.archlinux.org"
提供者=(AlexaTrafficRank(),GooglePageRank(),)
打印(“流量统计信息:%s”%(url))
对于p in提供商:
打印(“%s:%d”%(p.\u类\uuuuuuu.\uuuuu名称\uuuuu,p.get\u排名(url)))
这将为您提供一些见解

另外,我也做了一些搜索-确实有一个据说在这方面有帮助的。还有一个参考,你可以检查一下,看看它是否满足你的要求


PS:我没有测试过上述任何解决方案。

它会产生什么错误?以及堆栈?