我正在尝试从url打印一些信息,但如果找到某个文本,我想跳过打印,我有:
import urllib2
url_number = 1
url_number_str = number
a = 1
while a != 10:
f = urllib2.urlopen('http://example.com/?=' + str(url_number_str)
f_contents = f.read()
if f_contents != '{"Response":"Parse Error"}':
print f_contents
a += 1
url_number_str += 1因此,{"Response":"Parse Error"}是我想要查找的文本,以避免打印f.read()并加载下一个url (编号2)
发布于 2011-06-28 06:07:09
尽管你的问题有点不清楚,但试试这个:
f = urllib2.urlopen('http://example.com/?id=1000')
for line in f.readlines():
if line != '{"Response":"Parse Error"}':
print line这个循环遍历网页中的每一行,并在'{"Response":"Parse Error"}'处停止。
编辑:没关系,这可能就是你想要的:
f = urllib2.urlopen('http://example.com/?id=1000')
data = f.read()
if data != '{"Response":"Parse Error"}':
print data这将打印整个网页,除非它是'{"Response":"Parse Error"}'。
发布于 2011-06-28 06:09:51
read读取一块数据。此块的实际大小可能大于'{"Response":"Parse Error"}'。
因此,您应该使用RE或strstr like在读取的数据中搜索字符串(参见@harpyon的答案)。
发布于 2011-06-28 08:56:44
我想这就是你想要的:
a = 1
while a != 100:
f = urllib2.urlopen('http://example.com/?id=1000')
f_contents = f.read()
if f_contents != '{"Response":"Parse Error"}':
print f_contents
a += 1不过,如果您不想获得相同的页面100次,那么您可能忘记了在URL中添加a。
https://stackoverflow.com/questions/6499480
复制相似问题