如何用pycurl获取多个页面?
我想从一个网站获取很多页面,比如
curl "http://farmsubsidy.org/DE/browse?page=[0000-3603]" -o "de.#1"
但是我想用Python获取这些页面的数据,而不是保存成磁盘文件。
有人能发一段pycurl
的代码来实现这个吗?
或者用快速的urllib2
(不是一个一个地获取),如果可以的话,
要不就直接说“算了,curl更快更稳定”?谢谢!
6 个回答
1
你可以把这个放到一个bash脚本里,然后用一个循环来执行。
不过,用python来处理每个页面可能会更有效。你可以通过这个链接了解更多:http://www.securitytube.net/Crawling-the-Web-for-Fun-and-Profit-video.aspx。这样你就能获取到准确的数据,并且可以同时把这些数据保存到数据库里。想了解如何存储从网上获取的数据,可以看看这个链接:http://www.securitytube.net/Storing-Mined-Data-from-the-Web-for-Fun-and-Profit-video.aspx。
6
所以你遇到了两个问题,我来给你举个例子。注意,pycurl已经帮你处理了多线程的问题,也就是说它可以同时处理多个请求,而不是一个一个来,这样你就不用费力去实现了。
#! /usr/bin/env python
import sys, select, time
import pycurl,StringIO
c1 = pycurl.Curl()
c2 = pycurl.Curl()
c3 = pycurl.Curl()
c1.setopt(c1.URL, "http://www.python.org")
c2.setopt(c2.URL, "http://curl.haxx.se")
c3.setopt(c3.URL, "http://slashdot.org")
s1 = StringIO.StringIO()
s2 = StringIO.StringIO()
s3 = StringIO.StringIO()
c1.setopt(c1.WRITEFUNCTION, s1.write)
c2.setopt(c2.WRITEFUNCTION, s2.write)
c3.setopt(c3.WRITEFUNCTION, s3.write)
m = pycurl.CurlMulti()
m.add_handle(c1)
m.add_handle(c2)
m.add_handle(c3)
# Number of seconds to wait for a timeout to happen
SELECT_TIMEOUT = 1.0
# Stir the state machine into action
while 1:
ret, num_handles = m.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
# Keep going until all the connections have terminated
while num_handles:
# The select method uses fdset internally to determine which file descriptors
# to check.
m.select(SELECT_TIMEOUT)
while 1:
ret, num_handles = m.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
# Cleanup
m.remove_handle(c3)
m.remove_handle(c2)
m.remove_handle(c1)
m.close()
c1.close()
c2.close()
c3.close()
print "http://www.python.org is ",s1.getvalue()
print "http://curl.haxx.se is ",s2.getvalue()
print "http://slashdot.org is ",s3.getvalue()
最后,这段代码主要是基于pycurl网站上的一个例子。=.=
也许你真的应该去看看文档,很多人花了大量时间在这上面。
3
这里有一个基于urllib2和线程的解决方案。
import urllib2
from threading import Thread
BASE_URL = 'http://farmsubsidy.org/DE/browse?page='
NUM_RANGE = range(0000, 3603)
THREADS = 2
def main():
for nums in split_seq(NUM_RANGE, THREADS):
t = Spider(BASE_URL, nums)
t.start()
def split_seq(seq, num_pieces):
start = 0
for i in xrange(num_pieces):
stop = start + len(seq[i::num_pieces])
yield seq[start:stop]
start = stop
class Spider(Thread):
def __init__(self, base_url, nums):
Thread.__init__(self)
self.base_url = base_url
self.nums = nums
def run(self):
for num in self.nums:
url = '%s%s' % (self.base_url, num)
data = urllib2.urlopen(url).read()
print data
if __name__ == '__main__':
main()