某公司给来的邮件测试题,从优酷视频列表页抓前5页的视频的标题和链接。用python写了个,以前都没怎么用过,算是进步了。。。。

 

 
  
  1. #Python version:2.6.6 
  2. #filename:youkuParser 
  3. import urllib2 
  4. import codecs 
  5. from sgmllib import SGMLParser 
  6. class URLLister(SGMLParser):    #继承SGMLParser 
  7.     def __init__(self): 
  8.         SGMLParser.__init__(self
  9.     def start_a(self,attrs):    #对超链接标签进行筛选判断 
  10.         if len(attrs)==4
  11.             if ((attrs[0][0]=='href') & (attrs[1][0]=='title') & (attrs[2][0]=='target') & (attrs[2][1]=='video')): 
  12.                 f = codecs.open('out.txt','a','utf-8')    #从attrs中输出到文件 
  13.                 title = unicode(attrs[1][1],'utf-8'
  14.                 link = unicode(attrs[0][1],'utf-8'
  15.                 f.write(title) 
  16.                 f.write('\n'
  17.                 f.write(link) 
  18.                 f.write('\n\n'
  19.                 f.close() 
  20.  
  21. class NextPage(SGMLParser):   #抓取下一页的链接 
  22.     nextPage = '' 
  23.     def __init__(self): 
  24.         SGMLParser.__init__(self
  25.     def start_a(self,attrs): 
  26.         if len(attrs)==2
  27.             if((attrs[0][0]=='href') & (attrs[1][0]=='charset') & (attrs[1][1]=='742-4-1-999')): 
  28.                 nextPage = "http://www.youku.com" + attrs[0][1]   #构造超链接 
  29.                 page.nextPage = nextPage 
  30. sock = urllib2.urlopen("http://www.youku.com/v_showlist/t2d1c94g235.html"
  31. HtmlSource = sock.read() 
  32. sock.close() 
  33. print 'Hello' 
  34. print  
  35. for i in range(1,6):   #对前几页循环执行 
  36.     lister = URLLister() 
  37.     lister.feed(HtmlSource) 
  38.     page = NextPage() 
  39.     page.feed(HtmlSource) 
  40.     sock = urllib2.urlopen(page.nextPage) 
  41.     HtmlSource = sock.read() 
  42.     sock.close() 
  43. print 'Done'