有效地加入python的URL,而无需字符串串联

发布于 2025-01-22 13:59:28 字数 678 浏览 1 评论 0原文

我正在尝试加入一个URL,但目前有一种非常手动的方法来执行此操作,并想知道是否有更有效的方法。

我有使用urlparse进行解析的主页。我也有最终链接,我试图通过该方案和域名加入。代码就是这样:

url = 'https://www.windex.com/en-us'
link = '/en-us/products/outdoor-sprayer'

parsed_url = urlparse(url)
full_url = parsed_url.scheme + '://' + parsed_url.netloc + link

给出 https://www.windex.com/ En-US/Products/户外喷雾器是正确的,并将我引向正确的页面。除了字符串串联以外,还有更好的方法吗?我尝试了urljoin,但结果错误:

urljoin(parsed_url.scheme, parsed_url.netloc, link)
Output: 'www.windex.com'

非常感谢

I am trying to join a url but at the moment have a very manual way of doing it and wondered if there is a more efficient way.

I have the homepage with I have parsed using urlparse. I also have the end link which I am trying to join with both the scheme and the domain name. The code is as such:

url = 'https://www.windex.com/en-us'
link = '/en-us/products/outdoor-sprayer'

parsed_url = urlparse(url)
full_url = parsed_url.scheme + '://' + parsed_url.netloc + link

This gives https://www.windex.com/en-us/products/outdoor-sprayer which is correct and directs me to the right page. Is there a better way to do this other than string concatenation? I tried urljoin as follows but got the wrong result:

urljoin(parsed_url.scheme, parsed_url.netloc, link)
Output: 'www.windex.com'

Many Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萧瑟寒风 2025-01-29 13:59:28

如果您的意思是 urllib.parse.urlse.urljoin 然后,您以错误的方式使用它,因为它仅需要baseurl

import urllib

url = 'https://www.windex.com/en-us/'
link = '/en-us/products/outdoor-sprayer'

full_url = urllib.parse.urljoin(url, link)

If you mean urllib.parse.urljoin then you use it in wrong way because it needs only base and url

import urllib

url = 'https://www.windex.com/en-us/'
link = '/en-us/products/outdoor-sprayer'

full_url = urllib.parse.urljoin(url, link)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文