zch*_*zch -1 python url urllib2
我刚写了一个脚本,意思是通过字母表找到所有无人认领的四个字母的推特名字(实际上只是为了练习,因为我是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
Run Code Online (Sandbox Code Playgroud)
运行此代码返回以下错误:
SyntaxError:第29行文件name.py中的非ASCII字符'\ xe2',但未声明编码; 有关详细信息,请参阅http://www.python.org/peps/pep-0263.html
在访问该链接并进行其他搜索后,我在文档顶部添加了以下行:
# coding: utf-8
Run Code Online (Sandbox Code Playgroud)
现在,虽然它不再返回错误,但似乎没有任何事情发生.我添加了这条线
print src
Run Code Online (Sandbox Code Playgroud)
应该打印每个网址的html,但是当我运行时没有任何反应.任何建议将不胜感激.
您可以通过使用来摆脱过多的嵌套 itertools.product
from itertools import product
for d_one, d_two, d_three, d_four in product(letters, repeat=4):
...
Run Code Online (Sandbox Code Playgroud)
您可以使用,而不是定义字母列表 strings.ascii_lowercase
你应该告诉urlopen你正在使用哪个协议(http)
url = "http://twitter.com/" + d_one + d_two + d_three + d_four
Run Code Online (Sandbox Code Playgroud)
此外,当你这样做让不存在的页面,的urlopen提出了404
,所以你应该检查这,而不是看网页文本