Wal*_*Cat 3 html python lxml absolute-path python-2.7
使用lxml,如何使用绝对链接全局替换所有src属性?
这是一个示例代码,其中还包括<a href>:
from lxml import etree, html
import urlparse
def fix_links(content, absolute_prefix):
"""
Rewrite relative links to be absolute links based on certain URL.
@param content: HTML snippet as a string
"""
if type(content) == str:
content = content.decode("utf-8")
parser = etree.HTMLParser()
content = content.strip()
tree = html.fragment_fromstring(content, create_parent=True)
def join(base, url):
"""
Join relative URL
"""
if not (url.startswith("/") or "://" in url):
return urlparse.urljoin(base, url)
else:
# Already absolute
return url
for node in tree.xpath('//*[@src]'):
url = node.get('src')
url = join(absolute_prefix, url)
node.set('src', url)
for node in tree.xpath('//*[@href]'):
href = node.get('href')
url = join(absolute_prefix, href)
node.set('href', url)
data = etree.tostring(tree, pretty_print=False, encoding="utf-8")
return data
Run Code Online (Sandbox Code Playgroud)
我不确定什么时候添加的,但从lxml.fromstring()现在开始创建的文档有一个名为 的方法make_links_absolute。从文档中:
make_links_absolute(base_href,resolve_base_href = True):
这使得文档中的所有链接都是绝对链接,假设 base_href 是文档的 URL。因此,如果您传递 base_href="http://localhost/foo/bar.html" 并且有一个指向 baz.html 的链接,该链接将被重写为http://localhost/foo/baz.html。
如果resolve_base_href为true,那么任何标签都会被考虑在内(只需调用self.resolve_base_href())。
| 归档时间: |
|
| 查看次数: |
2188 次 |
| 最近记录: |