如何从python中的资源URL获取完整的URL

2024-10-03 06:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在web页面上,当分别嵌入<img><link><script>标记时,图像、css和javascript等资源将由客户端的web浏览器加载。在

资源URL可以采用不同的形式,可以是完整的URL,例如:

http://cdn.mysite.com/images/animage.jpg

它可以是相对路径:

^{pr2}$

或者只是对根的引用

/images/animage.jpg

如何在python中创建一个函数,它获取页面的URL和其中资源的URL,并确保返回完整的URL?在

例如:

def resource_url(page,resource):
    ## if the resource is a full URL, return that
    ## if not, use the page URL and the resource to return the full URL

Tags: theweburlimgreturnifpagelink
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:01
from urlparse import urljoin

def resource_url(page, resource):
  if not resource.startswith(page):
    # doesn't start with http://example.com
    resource = urljoin(page, resource)
  return resource

相关问题 更多 >