How to formally insert URL space (%20) using Python? [duplicate]

坚强是说给别人听的谎言 提交于 2019-12-10 15:35:51

问题


When a mutli-word search term is entered in ebay, the resultant URL looks something like (for example "demarini cf5 cf12"):

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

I wish to construct this URL in Python so it can be accessed directly. So it's case of concatenating the base URL:

http://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=

... with the search term. Right now. I am adding the %20 for the spaces explicately thus:

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

What is a more formal way of doing this in Python? I believe the name for this sort of task is URL encoding?


回答1:


It's simple use urllib library import urllib

finalurl = baseUrl + urllib.quote(searchterm)

you can use quote_plus() to add + insted of %20 to undo this use

urllib.unquote(str)


来源:https://stackoverflow.com/questions/32762219/how-to-formally-insert-url-space-20-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!