我正在制作一个可以解析html并从中获取图片的应用程序。解析是很容易使用美丽的汤和下载的html和图像,也适用于urllib2。
我确实在使用urlparse从相对路径中创建绝对路径时遇到了问题。这个问题最好用一个例子来解释:
>>> import urlparse
>>> urlparse.urljoin("http://www.example.com/", "../test.png")
'http://www.example.com/../test.png'如您所见,urlparse不会去掉../。这在我尝试下载镜像时出现了一个问题:
HTTPError: HTTP Error 400: Bad Request在urllib中有没有解决这个问题的方法?
发布于 2010-11-07 01:48:37
我认为你能做的最好的事情就是预先解析原始的URL,然后检查路径部分。一个简单的测试是
if len(urlparse.urlparse(baseurl).path) > 1:然后,您可以将其与demas建议的索引相结合。例如:
start_offset = (len(urlparse.urlparse(baseurl).path) <= 1) and 2 or 0
img_url = urlparse.urljoin("http://www.example.com/", "../test.png"[start_offset:])这样,您就不会尝试转到根URL的父级。
发布于 2010-11-07 01:30:11
"..“将为您打开一个目录(“.是当前目录),因此将其与域名url组合在一起没有多大意义。也许你需要的是:
>>> urlparse.urljoin("http://www.example.com","./test.png")
'http://www.example.com/test.png'发布于 2010-11-08 03:50:11
如果您希望/../test的含义与文件系统中的/test相同,那么您可以使用normpath()
>>> url = urlparse.urljoin("http://example.com/", "../test")
>>> p = urlparse.urlparse(url)
>>> path = posixpath.normpath(p.path)
>>> urlparse.urlunparse((p.scheme, p.netloc, path, p.params, p.query,p.fragment))
'http://example.com/test'https://stackoverflow.com/questions/4114225
复制相似问题