2014-06-29 168 views
1

我想从html页面中只提取相关的url;有人有这个提示:从html页面获取相对链接

find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE) 

但它返回:从页面

1 /所有的绝对和相对URL。

2 /该网址可以通过""''随机报出。

+0

你可以尝试这样的东西:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags? –

回答

4

使用the tool for the jobHTML parser,如BeautifulSoup

可以pass a function作为一个属性值find_all(),并检查是否href开始与http

from bs4 import BeautifulSoup 

data = """ 
<div> 
<a href="http://google.com">test1</a> 
<a href="test2">test2</a> 
<a href="http://amazon.com">test3</a> 
<a href="here/we/go">test4</a> 
</div> 
""" 
soup = BeautifulSoup(data) 
print soup.find_all('a', href=lambda x: not x.startswith('http')) 

或者,使用urlparsechecking for network location part

def is_relative(url): 
    return not bool(urlparse.urlparse(url).netloc) 

print soup.find_all('a', href=is_relative) 

这两种解决方案打印:

[<a href="test2">test2</a>, 
<a href="here/we/go">test4</a>]