我知道这可能听起来很荒谬,但是是否可以使用 urllib2 打开 URL,以便最多只返回一组行数?
原因是减少加载时间,特别是对于我正在使用的非常大的页面。例如,这是我的页面:
1. <html>
2. <head>
3. <title>Hello!</title>
4. </head>
5. <body>
6. <p>Hi there.</p>
7. </body>
8. </html>
假设我要打开页面到第 5 行,然后在阅读后打印它,它会给我:
1. <html>
2. <head>
3. <title>Hello!</title>
4. </head>
5. <body>
这可能吗?
最佳答案
当然,您可以使用readline()
代替read()
import urllib2
req = urllib2.Request('http://www.python.org')
response = urllib2.urlopen(req)
lines = ""
for x in range(10):
lines += response.readline()
print(lines)
关于python - 使用 urllib2 打开的 URL 是否可以限制返回的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973796/