Python 如何打开名称由连续数字组成的网站页面(http://website/#.html)
所以说我有这个Python 如何打开名称由连续数字组成的网站页面(http://website/#.html),python,Python,所以说我有这个 global a a = 1 def newre(): global a a += 1 b = str(a) print b op = urlopen('http://website/' + b + '.html') ops = op.read() 它不起作用,因为我猜它可能在函数中,但如何使它在每次运行类时,op中的b都比以前高1?每次更改a时,都需要更改b 这是你发布的全部代码吗?这里似乎缺少一些东西,如何多次调用urlopen?为什么要使用
global a
a = 1
def newre():
global a
a += 1
b = str(a)
print b
op = urlopen('http://website/' + b + '.html')
ops = op.read()
它不起作用,因为我猜它可能在函数中,但如何使它在每次运行类时,op中的b都比以前高1?每次更改
a
时,都需要更改b
这是你发布的全部代码吗?这里似乎缺少一些东西,如何多次调用
urlopen
?为什么要使用globals和其他东西。这很简单,因为您正在尝试的有点像这样
contents = []
for i in range(10): # or whatever
url = 'http://website/' + str(i) + '.html'
content = urlopen(url)
contents.append(content)
另外,我建议您从一个好的Python教程开始。欢迎来到StackOverflow 看看你正确缩进的代码,我有点明白你想做什么。对此,我将使用python迭代器
class pageIter:
def __init__(self):
self.a = 0
def __iter__(self):
return (self)
def next(self):
""" Return the contents of the next page """
self.a += 1
#when no more, raise StopIteration to terminate
op = urlopen('http://website/' + str(a) + '.html')
return op.read()
it = pageIter()
for pageOp in it:
# do something with the next page until something happens
(或者只是简单地说)
现在,使用发电机:
def new_url(base_url, maxim):
i = 0
while i < maxim:
i = i+1
yield base_url % i
如果需要在不同时刻调用它并获取下一个连续名称,可以使用next()
:
我太清醒了,无法处理这个问题……它也不会起作用,因为你的缩进是错误的。请尝试重新格式化您的代码并编辑原始问题。世界上谁会这样缩进他们的代码?哎哟,对不起,我刚从我的程序中拿走了那个代码。忘了删除一些区域。或者在itertools.count(1)中使用
,如果您不知道在停止之前需要走多远的话。
我碰巧已经使用python一年了,但这只是一个我无法通过的问题。。。让我听起来好像我不擅长编程。
from urllib2 import urlopen
def urlIter(url, pages):
return (url.format(page) for page in pages)
for url in urlIter('http://website/{0}.html', range(1,20)):
pg = urlopen(url).read()
# do something with pg
def new_url(base_url, maxim):
i = 0
while i < maxim:
i = i+1
yield base_url % i
indexes = 10
base_url = "http://website/%i.html"
for url in new_url(base_url, indexes):
pg = urlopen(url).read()
............
gen_url = new_url(base_url, indexes)
url1 = next(gen_url)
.... do whatever here ....
#when you need it, you get a new url calling next():
url2 = next(gen_url)