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

Pyd*_*man 6 python url urllib urllib2 url-encoding

当在 ebay 中输入多词搜索词时,结果 URL 类似于(例如“demarini cf5 cf12”):

http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=demarini%20cf5%20cfc12
Run Code Online (Sandbox Code Playgroud)

我希望用 Python 构建这个 URL,以便可以直接访问它。所以这是连接基本 URL 的情况:

http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=
Run Code Online (Sandbox Code Playgroud)

...与搜索词。马上。我正在%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
Run Code Online (Sandbox Code Playgroud)

在 Python 中执行此操作的更正式方法是什么?我相信这种任务的名称是 URL 编码?

Jay*_*kar 9

使用urllib图书馆

import urllib
finalurl = baseUrl + urllib.parse.quote(searchterm)
Run Code Online (Sandbox Code Playgroud)

您可以使用 quote_plus() 添加 + %20 的插入来撤消此使用

urllib.parse.unquote(str)
Run Code Online (Sandbox Code Playgroud)

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