类型:转载 责任编辑: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:
• <a href= www.company.com>
• <A title="Link to homepage"
• 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)
网友回答:
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"
>"""
1. 解决跨行问题,用single line (?s)
2. 排除注释,直接把它们删了。
re.sub("(?s)<!--(.+?)-->", "", string)
3. 要解决大小写,用ignore case。(?i)
4. 要解决部分的链接,用urlparse类库
先把所有a标记找出来<a\s*(.*?)>,然后再一个一个找属性。不要太心急,divide and conquer
可以先使用re中的sub将所有注释替换成空,再分析链接。
对于链接的协议,常用的就几种,象http://, ftp://, mailto: 什么的,如果都没有就默认为http的就好了。