2010-11-06 38 views
2

我正在制作一个解析html并从中获取图片的应用程序。使用Beautiful Soup进行解析非常简单,下载html和图像也可以使用urllib2。Python urlparse:小问题

我确实有一个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中这个问题呢?

+0

的相对HREF =“../ test.png”的作品,但不href =“http://www.example.com/../test.png”? – 2010-11-06 17:46:53

回答

2

我认为你可以做的最好的是预解析原始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的父级。

+0

谢谢,我会走这条路,并执行类似的事情。 – Mew 2010-11-06 18:09:13

3

“..”会为您带来一个目录(“。”是当前目录),因此将其与域名url相结合没有多大意义。也许你需要的是:

>>> urlparse.urljoin("http://www.example.com","./test.png") 
'http://www.example.com/test.png' 
+0

尽管这是一个解决方案,但在我的情况下这不起作用:我的应用程序必须能够从任何网站检索图像。我不能用“./”替换“../”,因为这会破坏其他网站实际上应该去看父目录。 – Mew 2010-11-06 17:35:55

+0

urlparse.urljoin(“http://www.example.com/dir/”,“../test.png”) 适合我(我得到'http://www.example.com/test.png “)。我想这只是“..”并不意味着你有任何内容(什么是一个目录上的基础)。至少我不认为它确实如此。 – rtpg 2010-11-06 17:41:35

0
urlparse.urljoin("http://www.example.com/", "../test.png"[2:]) 

这是你需要什么?

+0

这与Dasuraga的解决方案有同样的问题:它只适用于某个网站,而打破其他网站。 – Mew 2010-11-06 17:37:33

1

如果您想那个/../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' 
+0

示例脚本:http://codepad.org/0pTNWWM6 – jfs 2010-11-07 20:09:55