使用Python检查多个服务中的现有账户

0 投票
2 回答
538 浏览
提问于 2025-04-16 20:00

我正在尝试使用urllib和urlib2来检查各种社交网络上是否存在公共用户资料。现在我卡在了检查www.live.com这一步。

比如说,如果我访问这个网址 http://spaces.live.com/profile.aspx?mem=Example@hotmail.com,如果这个mem参数里的邮箱存在,它会自动跳转到这个账户的资料页面,像这样 http://profile.live.com/cid-f5ee5e2a441e7771/,即使这个资料不是公开的。否则,如果账户不存在,就不会有任何跳转。

我应该怎么用URLError(或者其他方法)来检测这个跳转呢?有没有更好的方法?

编辑:

我自己解决了!!!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib2 
from urllib2 import HTTPError, URLError
nick=str(sys.argv[1])
pref_live="http://spaces.live.com/profile.aspx?mem="
suf_live_01="@hotmail.com"
try:  
    f = urllib2.urlopen( pref_live + nick + suf_live_01 )
    print f.read()  
    f.close()  
except HTTPError, e:  
    print "error"  
    print e.code  
except URLError, e:  
    print "error"  
    print e.reason  

如果错误是404,说明账户存在;如果是500,说明账户不存在。

编辑2:

这是最终的代码,感谢大家的帮助 :)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib2 
from urllib2 import HTTPError, URLError
prefix_live="http://spaces.live.com/profile.aspx?mem="
sufix_live=["@hotmail.com","@live.com"]
try:
    nick=str(sys.argv[1])
except:
    print "Username needed"
    print "Usage:"
    print sys.argv[0], "[username]"
    nick=''

def checking():
    for domain in sufix_live:
        try:  
            f = urllib2.urlopen( prefix_live + nick + domain )
            print f.read()    
            f.close()    
        except HTTPError, e:  
            if e.code == 404:
                print 'Yeah! %s%s exists' % (nick, domain) 
            elif e.code == 500:
                print 'Doh! %s%s Does NOT exists'% (nick, domain)
            else:
                print 'other error'
                print e.code
        except URLError, e:     
            print "There was an error"  
            print e.reason    

if nick != '':
    checking()

2 个回答

0

可以考虑使用mechanize这个模块。

它提供了urllib2的接口,还包含了很多方便的功能,可以帮助你浏览网站,比如解析内容、处理表单、处理重定向、管理 cookies 等等。

0

我想加个评论问问具体情况和代码示例,但可惜我还不能评论。不过我可以试着回答你的问题。

假设你在做这样的事情:

request = urllib2.Request('http://someurl.com')
response = urllib2.urlopen(request)
if response.geturl() != 'http://someurl.com':
    print "redirected"
else:
    print "not redirected"   

那么在第一种情况下,如果urllib2收到一个重定向代码(比如响应300),它会帮你处理重定向,并获取服务器重定向到的URL。

你可以通过检查response.geturl()的值来确认你是否真的被重定向了。

撰写回答