为什么我的Python脚本没有正确返回页面源?

时间:2012-08-13 04:07:20

标签: python url urllib2

我刚写了一个脚本,意思是通过字母表找到所有无人认领的四个字母的Twitter名称(实际上只是为了练习,因为我是Python的新手)。我写了几个以前的脚本,使用'urllib2'从网址获取网站html,但这次它似乎没有工作。这是我的剧本:

import urllib2

src=''
url=''
print "finding four-letter @usernames on twitter..."
d_one=''
d_two=''
d_three=''
d_four=''
n_one=0
n_two=0
n_three=0
n_four=0
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

while (n_one > 26):
    while(n_two > 26):
        while (n_three > 26):
            while (n_four > 26):
                d_one=letters[n_one]
                d_two=letters[n_two]
                d_three=letters[n_three]
                d_four=letters[n_four]
                url = "twitter.com/" + d_one + d_two + d_three + d_four

                src=urllib2.urlopen(url)
                src=src.read()
                if (src.find('Sorry, that page doesn’t exist!') >= 0):
                    print "nope"
                    n_four+=1
                else:
                    print url
                    n_four+=1
            n_three+=1
            n_four=0
        n_two+=1
        n_three=0
        n_four=0
    n_one+=1    
    n_two=0
    n_three=0
    n_four=0

运行此代码会返回以下错误:

  

SyntaxError:第29行文件name.py中的非ASCII字符'\ xe2',   但没有声明编码;见http://www.python.org/peps/pep-0263.html   详情

在访问该链接并进行其他搜索后,我在文档顶部添加了以下行:

# coding: utf-8

现在,虽然它不再返回错误,但似乎没有发生任何事情。我添加了一行

print src

应该打印每个网址的html,但是当我运行时没有任何反应。任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:5)

您可以使用itertools.product

摆脱过多的嵌套
from itertools import product
for d_one, d_two, d_three, d_four in product(letters, repeat=4):
    ...

您可以使用strings.ascii_lowercase

,而不是定义字母列表

你应该告诉urlopen你正在使用哪个协议(http)

url = "http://twitter.com/" + d_one + d_two + d_three + d_four

当你获取一个不存在的页面时,urlopen会引发404,所以你应该检查它而不是查看页面文本

答案 1 :(得分:1)

好吧,您初始化n_one=0,然后执行循环while (n_one > 26)。当Python第一次遇到它时,它会看到while (0 > 26),这显然是假的,因此它会跳过整个循环。

正如gnibbler的回答告诉你的那样,无论如何都有更简洁的循环方法。