从页面上的相对URL重建绝对URL

Yar*_*rin 21 html python url-parsing

给定页面的绝对URL以及在该页面中找到的相对链接,是否有办法a)明确重建或b)尽力重建相对链接的绝对URL?

在我的情况下,我正在使用漂亮的汤从一个给定的URL读取一个html文件,删除所有img标记源,并尝试构建页面图像的绝对URL列表.

到目前为止我的Python函数看起来像:

function get_image_url(page_url,image_src):

    from urlparse import urlparse
    # parsed = urlparse('http://user:pass@NetLoc:80/path;parameters?query=argument#fragment')
    parsed = urlparse(page_url)
    url_base = parsed.netloc
    url_path = parsed.path

    if src.find('http') == 0:
        # It's an absolute URL, do nothing.
        pass
    elif src.find('/') == 0:
        # If it's a root URL, append it to the base URL:
        src = 'http://' + url_base + src
    else:
        # If it's a relative URL, ?
Run Code Online (Sandbox Code Playgroud)

注意:不需要Python答案,只需要逻辑.

Not*_*fer 40

非常简单:

>>> from urlparse import urljoin
>>> urljoin('http://mysite.com/foo/bar/x.html', '../../images/img.png')
'http://mysite.com/images/img.png'
Run Code Online (Sandbox Code Playgroud)

  • urlparse模块在Python 3中重命名为urllib.parse.因此,`来自urllib.parse import urljoin` (13认同)

Gar*_*ees 16

用于urllib.parse.urljoin根据基本URL解析(可能是相对的)URL.

但是,网页的基本URL不一定与您从中提取文档的URL相同,因为HTML允许页面通过BASE元素指定其首选基本URL .您需要的逻辑如下:

base_url = page_url
head = document.getElementsByTagName('head')[0]
for base in head.getElementsByTagName('base'):
    if base.hasAttribute('href'):
        base_url = urllib.parse.urljoin(base_url, base.getAttribute('href'))
        # HTML5 4.2.3 "if there are multiple base elements with href
        # attributes, all but the first are ignored."
        break
Run Code Online (Sandbox Code Playgroud)

(如果你正在解析XHTML,那么在理论上你应该考虑相当毛茸茸的XML Base规范.但你可以逃脱而不用担心,因为没有人真正使用XHTML.)