Bruno 'Shady'
Bruno 'Shady'

Reputation: 4516

How to fetch a website using threads or some other fast way?

I'm having a little trouble here to understand how threads work or build something with it.

I need to download several webpages changing one value on the link (easy part) and get some information, but I'm using 'while' and it takes about 1 second or more to download a site with something like 60kb... My internet 5mb..

Could someone provide me the SIMPLEST example on how to do something similar?

Upvotes: 1

Views: 172

Answers (2)

Piotr Dobrogost
Piotr Dobrogost

Reputation: 42425

From Advanced Usage: Asynchronous Requests

from requests import async

urls = [
    'http://python-requests.org',
    'http://httpbin.org',
    'http://python-guide.org',
    'http://kennethreitz.com'
]

rs = [async.get(u) for u in urls]
async.map(rs)

This is not using threads but works the same - requests are being made concurrently.

Upvotes: 3

PabloG
PabloG

Reputation: 26715

Extracted from here

      #!/usr/bin/env python
      import Queue
      import threading
      import urllib2
      import time

      hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
      "http://ibm.com", "http://apple.com"]

      queue = Queue.Queue()

      class ThreadUrl(threading.Thread):
      """Threaded Url Grab"""
        def __init__(self, queue):
          threading.Thread.__init__(self)
          self.queue = queue

        def run(self):
          while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and prints first 1024 bytes of page
            url = urllib2.urlopen(host)
            print url.read(1024)

            #signals to queue job is done
            self.queue.task_done()

      start = time.time()
      def main():

        #spawn a pool of threads, and pass them queue instance 
        for i in range(5):
          t = ThreadUrl(queue)
          t.setDaemon(True)
          t.start()

       #populate queue with data   
          for host in hosts:
            queue.put(host)

       #wait on the queue until everything has been processed     
       queue.join()

      main()
      print "Elapsed Time: %s" % (time.time() - start)

Upvotes: 0

Related Questions