Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #53089

Re: Improving the web page download code.

Path csiph.com!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <python@mrabarnett.plus.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'read.': 0.03; "'',": 0.07; 'discard': 0.07; 'expressions': 0.07; 'modify': 0.07; 'none:': 0.07; 'puts': 0.07; 'append': 0.09; 'data:': 0.09; 'exit': 0.09; 'f.close()': 0.09; 'newline': 0.09; 'pages.': 0.09; 'parsing': 0.09; 'prefix': 0.09; 'suggestions.': 0.09; 'sys,': 0.09; 'python': 0.11; 'def': 0.12; 'wrote': 0.14; 'thread': 0.14; "'__main__':": 0.16; "'w')": 0.16; '.join': 0.16; 'chunks': 0.16; 'enough.': 0.16; 'exist.': 0.16; 'file.close()': 0.16; 'finish.': 0.16; 'from:addr:mrabarnett.plus.com': 0.16; 'from:addr:python': 0.16; 'from:name:mrab': 0.16; 'graceful': 0.16; 'initially,': 0.16; 'iteration': 0.16; 'lambda': 0.16; 'loop.': 0.16; 'message- id:@mrabarnett.plus.com': 0.16; 'robust.': 0.16; 'sees': 0.16; 'sentinel': 0.16; 'subject:download': 0.16; 'sys.exit(0)': 0.16; 'thread,': 0.16; 'timeout': 0.16; 'urllib2,': 0.16; 'xrange': 0.16; 'elements': 0.16; 'exception': 0.16; 'wrote:': 0.18; 'code.': 0.18; 'all,': 0.19; 'subject:page': 0.19; 'code,': 0.22; 'programming': 0.22; 'import': 0.22; 'preferred': 0.22; 'print': 0.22; 'header:User-Agent:1': 0.23; 'bytes': 0.24; 'second': 0.26; 'pass': 0.26; 'downloaded': 0.26; 'gets': 0.27; 'header:In-Reply- To:1': 0.27; 'function': 0.29; '[1]': 0.29; 'raise': 0.29; 'characters': 0.30; 'mode': 0.30; 'see,': 0.30; 'asked': 0.31; 'code': 0.31; 'lines': 0.31; 'file:': 0.31; 'os,': 0.31; 'restricted': 0.31; 'file': 0.32; 'class': 0.32; 'probably': 0.32; 'stuff': 0.32; 'regular': 0.32; 'open': 0.33; 'running': 0.33; 'skip:# 10': 0.33; 'subject:the': 0.34; 'except': 0.35; 'but': 0.35; 'dies': 0.36; 'doing': 0.36; 'method': 0.36; 'possible': 0.36; 'should': 0.36; 'two': 0.37; 'skip:o 20': 0.38; 'server': 0.38; 'initially': 0.38; 'to:addr:python-list': 0.38; 'resource': 0.38; 'sure': 0.39; 'to:addr:python.org': 0.39; 'enough': 0.39; 'skip:u 10': 0.60; 'read': 0.60; 'middle': 0.60; 'signal': 0.60; 'break': 0.61; 'skip:o 30': 0.61; 'first': 0.61; 'back': 0.62; 'such': 0.63; 'soon': 0.63; 'more': 0.64; 'finally': 0.65; 'land': 0.65; 'worth': 0.66; 'due': 0.66; 'header:Reply-To:1': 0.67; 'default': 0.69; 'reply-to:no real name:2**0': 0.71; 'miss': 0.74; 'improvement': 0.84; 'reply-to:addr:python.org': 0.84; 'instantly.': 0.91
X-CM-Score 0.00
X-CNFS-Analysis v=2.1 cv=bL0vfpOZ c=1 sm=1 tr=0 a=0nF1XD0wxitMEM03M9B4ZQ==:117 a=0nF1XD0wxitMEM03M9B4ZQ==:17 a=0Bzu9jTXAAAA:8 a=0kkAYlmtguIA:10 a=O3gwnNBEnR8A:10 a=ihvODaAuJD4A:10 a=OUOv7kDek9cA:10 a=8nJEP1OIZ-IA:10 a=EBOSESyhAAAA:8 a=8AHkEIZyAAAA:8 a=qkRsfQMCdm0A:10 a=4oosK9W4AAAA:8 a=IL5kGFMm7YwkQSqjR3EA:9 a=wPNLvfGTeEIA:10
X-AUTH mrabarnett:2500
Date Tue, 27 Aug 2013 21:19:59 +0100
From MRAB <python@mrabarnett.plus.com>
User-Agent Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130801 Thunderbird/17.0.8
MIME-Version 1.0
To python-list@python.org
Subject Re: Improving the web page download code.
References <ff1a229a-affa-4d6f-aeab-55762c48a160@googlegroups.com>
In-Reply-To <ff1a229a-affa-4d6f-aeab-55762c48a160@googlegroups.com>
Content-Type text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding 7bit
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
Reply-To python-list@python.org
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.281.1377634802.19984.python-list@python.org> (permalink)
Lines 104
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1377634802 news.xs4all.nl 15865 [2001:888:2000:d::a6]:50386
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:53089

Show key headers only | View raw


On 27/08/2013 20:41, mukesh tiwari wrote:
> Hello All,
> I am doing web stuff first time in python so I am looking for suggestions. I wrote this code to download the title of webpages using as much less resource ( server time, data download)  as possible and should be fast enough. Initially I used BeautifulSoup for parsing but the person who is going to use this code asked me not to use this and use regular expressions ( The reason was BeautifulSoup is not fast enough ? ). Also initially, I was downloading the the whole page but finally I restricted to only 30000 characters to get the title of almost all the pages. Write now I can see only two shortcomings of this code, one when I kill the code by SIGINT ( ctrl-c ) then it dies instantly. I can modify this code to process all the elements in queue and let it die. The second is one IO call per iteration in download url function ( May be I can use async IO call but I am not sure ). I don't have much web programming experience so I am looking for suggestion to make it more robust. top-1m.c
sv
>   is file downloaded from alexa[1]. Also some suggestions to write more idiomatic python code.
>
> -Mukesh Tiwari
>
> [1]http://www.alexa.com/topsites.
>
>
> import urllib2, os, socket, Queue, thread, signal, sys, re
>
>
> class Downloader():
>
> 	def __init__( self ):
> 		self.q = Queue.Queue( 200 )
> 		self.count = 0
> 	
>
>
> 	def downloadurl( self ) :
> 		#open a file in append mode and write the result ( Improvement think of writing in chunks )
> 		with open('titleoutput.dat', 'a+' ) as file :	
> 			while True :
> 				try :
> 					url = self.q.get( )
> 					data = urllib2.urlopen ( url , data = None , timeout = 10 ).read( 30000 )
> 					regex = re.compile('<title.*>(.*?)</title>' , re.IGNORECASE)
> 					#Read data line by line and as soon you find the title go out of loop.
> 					#title = None
> 					#for r in data:
> 					#	if not r :
> 					#		raise StopIteration
> 					#	else:
> 					#		title = regex.search( r )
> 					#		if title is not None: break
>
> 					title = regex.search( data )
> 					result =  ', '.join ( [ url , title.group(1) ] )
> 					#data.close()
> 					file.write(''.join( [ result , '\n' ] ) )
> 				except urllib2.HTTPError as e:
> 				       print ''.join ( [ url, '  ', str ( e ) ] )
> 				except urllib2.URLError as e:
> 					print ''.join ( [ url, '  ', str ( e ) ] )
> 				except Exception as e :
> 					print ''.join ( [ url, '  ', str( e )  ] )
> 			#With block python calls file.close() automatically.		
> 				
>
> 	def createurl ( self ) :
>
> 		#check if file exist. If not then create one with default value of 0 bytes read.
> 		if os.path.exists('bytesread.dat'):
> 			f = open ( 'bytesread.dat','r')
> 			self.count = int ( f.readline() )
> 					
> 		else:
> 			f=open('bytesread.dat','w')
> 			f.write('0\n')
> 			f.close()
>
> 		#Reading data in chunks is fast but we can miss some sites due to reading the data in chunks( It's worth missing because reading is very fast)
> 		with open('top-1m.csv', 'r') as file:
> 			prefix = ''
> 			file.seek(  self.count * 1024 )
> 			#you will land into the middle of bytes so discard upto newline
> 			if ( self.count ): file.readline()	
> 			for lines in iter ( lambda : file.read( 1024 ) , ''):
> 				l = lines.split('\n')
> 				n = len ( l )
> 				l[0] = ''.join( [ prefix , l[0] ] )
> 				for i in xrange ( n - 1 ) : self.q.put ( ''.join ( [ 'http://www.', l[i].split(',')[1] ] ) )
> 				prefix = l[n-1]
> 				self.count += 1
>
> 			
> 	#do graceful exit from here.
> 	def handleexception ( self , signal , frame) :
> 		with open('bytesread.dat', 'w') as file:
> 			print ''.join ( [ 'Number of bytes read ( probably unfinished ) ' , str ( self.count ) ] )
> 			file.write ( ''.join ( [ str ( self.count ) , '\n' ] ) )
> 			file.close()			
> 			sys.exit(0)
>
> if __name__== '__main__':
> 	u = Downloader()
> 	signal.signal( signal.SIGINT , u.handleexception)
> 	thread.start_new_thread ( u.createurl , () )
> 	for i in xrange ( 5 ) :
> 		thread.start_new_thread ( u.downloadurl , () )
> 	while True : pass
> 			
>
My preferred method when working with background threads is to put a 
sentinel such as None at the end and then when a worker gets an item 
from the queue and sees that it's the sentinel, it puts it back in the 
queue for the other workers to see, and then returns (terminates). The 
main thread can then call each worker thread's .join method to wait for 
it to finish. You currently have the main thread running in a 'busy 
loop', consuming processing time doing nothing!

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Improving the web page download code. mukesh tiwari <mukeshtiwari.iiitm@gmail.com> - 2013-08-27 12:41 -0700
  Re: Improving the web page download code. MRAB <python@mrabarnett.plus.com> - 2013-08-27 21:19 +0100
    Re: Improving the web page download code. mukesh tiwari <mukeshtiwari.iiitm@gmail.com> - 2013-08-27 13:53 -0700
      Re: Improving the web page download code. MRAB <python@mrabarnett.plus.com> - 2013-08-27 23:33 +0100
        Re: Improving the web page download code. mukesh tiwari <mukeshtiwari.iiitm@gmail.com> - 2013-08-27 23:23 -0700
          Re: Improving the web page download code. MRAB <python@mrabarnett.plus.com> - 2013-08-28 16:12 +0100
  Re: Improving the web page download code. Alister <alister.ware@ntlworld.com> - 2013-08-28 08:58 +0000

csiph-web