url = "http://www.baidu.com" try: page = urllib2.urlopen(url) except IOError as e: logging.error('Url open failed with exception: %s', e) return None html = page.read() print "HTML of the url:", html
regex = ur'meta.*charset=("?)(.*?)("|>)' match = re.search(regex, html) html_charset = 'utf-8' # default charset if match: html_charset = match.group(2) else: logging.error("Fail to match charset Regex for url:%s", url) logging.info(html) return html
if html_charset=="gb2312" or html_charset=="GBK": html_charset = "GB18030" elif html_charset=="iso-8859-1": html_charset = "latin-1" return html.decode(html_charset)
import HTMLParser import re import urlparse import logging
class MyParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.links = [] def handle_starttag(self, tag, attrs): if tag == "a": if len(attrs) == 0: pass else: for (k, v) in attrs: if k == "href" and v != "/" and v != "javascript:;" and v !="javascript:void(0)" and v != "#" and v != "": self.links.append(v)
# HtmlParser to find all links def get_sub_urls(cur_url, cur_html): # get the current scheme urlparser = urlparse.urlparse(cur_url)
# get all the sub href links myhtmlparser = MyParser() myhtmlparser.feed(cur_html) myhtmlparser.close() logging.info('get all sub urls succ of : %s ' % cur_url)
while not url_queue.empty(); url = url_queue.get() content = webpage_urlopen.webpage_urlopen(url, conf.crawl_timeout) //actions like saving pages sub_urls = webpage_parse.webpage_parse(content, url) for sub_url in sub_urls: url_queue.put(sub_url)
function main: url_queue = Queue.Queue() url_queue.put(init_url) crawl-request(url)
class ThreadUrl(threading.Thread): 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()
def main(): #populate queue with data for host in hosts: queue.put(host) #spawn a poll of threads, and pass them queue instance for i in range(5): t = ThreadUrl(queue) t.setDaemon(True) t.start()
#wait on the queue until everything has been processed cur_ths = threading.enumerate() print "cur enumerate threadings len:", len(cur_ths) for t in cur_ths: print "cur enumerate threadings:", t queue.join() main()