资讯   |   开发   |   选机中心   |   产品大全 | IBM | 惠普 | 联想 | 戴尔 | 苹果 | 神舟
更多: | 华硕 | 明基 | 方正 | 紫光 | TCL | 夏新 | 联宝 | 宏碁 | 七喜 | 长城 | 清华同方 | 海尔 | 三星 | 东芝 | 索尼 | 富士通 | LG | 技术 | ddnoon
当前位置:笔记本 > 软件开发 >
Advertisement
文章正文

Python中用正则表达式发掘网页中的超链接(Crawler)

类型:转载   责任编辑:asp.net   日期:2007/05/23


热门软件下载:


   

要求如下:  
   
  (a)   Hyperlink   tag   is   in   the   form   <a()   href(s)=(s)url   ()>,   where   (s)   is   whitespace,   ()  
  is   other   attribute.   Note   that  
   
  i.   ()   and   (s)   may   not   be   present.  
  ii.   a   and   href   are   case   insensitive.  
  iii.   Tag   can   span   on   multiple   line  
  iv.   Ignore   the   hyperlink   tags   which   are   inside   comment   tags   (   <!--   -->   )  
   
  Samples   of   hyperlink   tag:  
  &#8226;   <a   href=   www.company.com>  
  &#8226;   <A   title="Link   to   homepage"  
  &#8226;   href="http://www.company.com/index.html">  
   
  (b)   URLs   which   only   differ   in   fragment   (   i.e.   the   part   which   follows   #)   should   be   considered   to   be   the   same   page.   For   example,  
  http://www.cuhk.edu.hk/index.html   and   http://www.cuhk.edu.hk/index.html#people  
  are   same   page.  
   
  (c)   Only   need   to   consider   HTTP   URL  
   
  (d)   The   initial   link   is   a   HTTP   URL  
   
  我真是头疼死了,能不能用尽量少的RE来达到以上的要求。我是初学,所以水平很菜,写了一个也不知道问题在哪里。请各位DX帮帮忙好吗?急  
   
  hyperlink_pat   =   re.compile(r<\s*(A|a)\s+[^>]*?\s*?(href|HREF)\s*=\s*["\][^>]+?["\]\s*>)  
  comment_pat   =   re.compile(r<!--.*?-->)  
   
  #search   the   matched   patterns   through   the   HTML   source   content   string  
  match_comments   =   re.search(comment_pat,   html_source)  
  match_links   =   re.search(hyperlink_pat,   html_source)

网友回答:

发表者:xyzxyz1111

groups用于的到以匹配表达式中的括号括起来的位置,你的里面没有括号括号,所以groups()得不到任何值.group(0)得到整个匹配值的字符.group(1)   ...得到每个括号内匹配的值。  
  所以应该在里面添加若干括号,把你要提取的部分括起来。  
  r<\s*[Aa]{1}\s+[^>]*?[Hh][Rr][Ee][Ff]\s*=\s*["\]?([^>]+)?["\]?.*?>  
   
  然后试试这个结果的groups()  
    """<a  
      haid="sd>f"  
      href   =   "http://www.google.com"  
      hihi="wesdfh"  
   
      >"""  
  以及"""<a  
      haid="sdf"  
      href   =   "http://www.google.com"  
      hihi="wesdfh"  
   
      >"""  
 

发表者:shhgs

1.   解决跨行问题,用single   line   (?s)  
  2.   排除注释,直接把它们删了。  
        re.sub("(?s)<!--(.+?)-->",   "",   string)  
  3.   要解决大小写,用ignore   case。(?i)  
  4.   要解决部分的链接,用urlparse类库  
   
  先把所有a标记找出来<a\s*(.*?)>,然后再一个一个找属性。不要太心急,divide   and   conquer

发表者:limodou

可以先使用re中的sub将所有注释替换成空,再分析链接。  
   
  对于链接的协议,常用的就几种,象http://,   ftp://,   mailto:   什么的,如果都没有就默认为http的就好了。


 

 
热门推荐笔记本: 明基笔记本
相关文章:
webmaster:popbb@126.com   最佳浏览:1024X768 MSIE
©2007 popbb.net All Rights Reserved