【问题标题】:Get relative links from html page从html页面获取相对链接
【发布时间】:2014-08-19 19:28:09
【问题描述】:
我只想从 html 页面中提取相对 url;有人建议这样做:
find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)
但它会返回:
1/页面中的所有绝对和相对网址。
2/url 可以随机使用"" 或''。
【问题讨论】:
标签:
python
html
regex
html-parsing
【解决方案1】:
使用the tool for the job:HTML 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'))
或者,使用urlparse 和checking 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>]