如何使用Python正式插入URL空格(%20)?

10

当在eBay中输入一个多词搜索词时,生成的URL看起来像这样(例如“demarini cf5 cf12”):

http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=demarini%20cf5%20cfc12

我希望能够在Python中构建此URL以便可以直接访问。因此,它的处理方式是连接基本URL:
http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=

...使用搜索词。现在,我明确地为空格添加%20

baseUrl = 'http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw='
searchTerm = 'demarini cf5 cf12'
searchTerm = ('%20').join(searchTerm.split(' '))
finalUrl = baseUrl + searchTerm

在Python中更正式的做法是什么?我相信这种任务的名称是URL编码?


1
你可能想要使用 urllib.quote() - larsks
1
在URL的查询字符串中编码空格的正确方法是使用+符号。请参见WikipediaHTML规范。因此,当只编码一个键或值时应使用urllib.quote_plus(),或者当您有一个键值对字典或序列时使用urllib.urlencode() - Martijn Pieters
@MartijnPieters 感谢您一如既往的全面回答,Martijn。 - Pyderman
1个回答

16

使用urllib

import urllib
finalurl = baseUrl + urllib.parse.quote(searchterm)

您可以使用quote_plus()将+添加到URL中,而不是%20。

要撤消此操作,请使用

urllib.parse.unquote(str)
在Python 2中,分别使用urllib.quote()urllib.unquote()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接