追加号码列表
urllist = ['http://example.com',
'http://example1.com']
i = 0
while i < len(urllist):
source = urllib.urlopen(urllist[i]).read()
regex = '(\d{3})/">(\w+\s-\s\w+)</a>' # e.g. '435', 'Tom-Jerry'
p = re.compile(regex)
db = re.findall(p, source)
db = [tuple(filter(None, t)) for t in db]
hero_id = []
for j in db:
hero_id.append(j[0])
i += 1
print hero_id
需要注意的是:db = [tuple(filter(None, t)) for t in db]
db
是这样的元组的列表:[('564', 'Tom', 'Jerry'), ('321', 'X-man', 'Hulk')]
。在hero_id = []
线上,一切都像一个魅力。 for foop需要附加每个数字(来自urllist
的每个网址)。它的部分工作。在末尾hero_id
列表只包含最后一个网址中的数字(之前的数字已消失)。想法?追加号码列表
那是因为你在“而”(hero_id = []
)
将每一次迭代hero_id设置为空列表刚过i = 0
也可以简单地像这样的代码:
urllist = ['http://example.com', 'http://example1.com']
hero_id = []
for url in urllist:
db = re.findall('(\d{3})/">(\w+\s-\s\w+)</a>', urllib.urlopen(url).read(), re.DOTALL)
for j in db:
hero_id.append(tuple(filter(None, j))[0])
print hero_id
由于您的hero_id在while循环中设置,因此每次迭代都会覆盖它。 使您的hero_id变量为全局变量,并且不要重置它。
hero_id = []
while():
#your code
这已经是全球性的 – lolopop 2013-03-09 21:25:01
范围确实与此无关。 Python不会用块创建一个新的范围,只能用函数创建。 – 2013-03-09 21:25:56
啊是的。由于代码中没有显示外部声明,所以我有点困惑。改变了答案。谢谢。 – 2013-03-09 21:27:34
使用'requests'库,或粘到STDLIB,使用'urllib2.urlopen'替代将是一个好主意...... – 2013-03-09 21:43:49
请求并没有真正necesarry,除非你需要aditional的数据发送到该网址或使用或代理或其他高级设置,虽然我同意urllib2比urllib更好,但这是nutship的决定,不是我的。 – 2013-03-09 21:49:49