我通常的查找完整url的方法是:
resp = urllib.request.urlopen('http://www.example.com')
base_url = resp.geturl()
# find the wanted (relative) url in the resp by using BeautifulSoup4
full_url = urljoin(base_url, relative_url)然而,对于一些网站,比如http://www.titanquest.net/tq-forum/forums/72-Underlord,base_url和full_url是错误的,因为url被重写了(我假设),如下所示:
>>> full_url
'http://www.titanquest.net/tq-forum/forums/72-Underlord'
>>> relative_url
'threads/43456-Epic-items?s=26260c54fd856499bff7a57e3c7ceb94'
>>> urljoin(full_url, relative_url)
'http://www.titanquest.net/tq-forum/forums/threads/43456-Epic-items?s=26260c54fd856499bff7a57e3c7ceb94'正确的url应该是:
http://www.titanquest.net/tq-forum/threads/43456-Epic-items?s=26260c54fd856499bff7a57e3c7ceb94我的问题是如何生成正确的base_url和full_url。
发布于 2012-09-26 14:59:19
您的浏览器通常确实使用当前页面的位置作为相对URL的基础,并且您使用urljoin可以正确地模拟这种行为。
但是,如果返回的超文本标记语言包含 tag,浏览器将使用由该标记命名的url作为解析相对url的基础。<base />标签是HTML头的一部分。
您需要解析http://www.titanquest.net/tq-forum/forums/72-Underlord的响应以确定是否存在这样的标记,然后使用其值而不是页面的URL来确定相对URL。<base href="link" />链接值本身可以是相对,在这种情况下,您必须首先根据文档位置将其设置为绝对。
在这种情况下,网页包含这样的<base />标记:
<base href="http://www.titanquest.net/tq-forum/" /><!--[if IE]></base><![endif]-->https://stackoverflow.com/questions/12595931
复制相似问题