Python 爬虫 URL中存在中文或特殊符号无法请求的解决方法

转自 :https://blog.csdn.net/hanchaobiao/article/details/72863277

https://blog.csdn.net/cc9200/article/details/79999741

  1.  
  2. from urllib.parse import quote

  3. import string

  4.  
  5. #解决请求路径中含义中文或特殊字符

  6. url_ = quote(new_url, safe=string.printable);

  7.  

比如

r=requests.get('www.xxx.com/?city=上海')

这时候可能会导致urlerror,之所以说可能,是因为有的网站后台可能有转码机制,特别是大网站,他们会把地址做一次转码。

对于那些没有做转码的站,则需要自己先转码,转成类似于这种:

'%E4%B8%8A%E6%B5%B7'   ‘上海’

这是中文字符的编码格式,16进制表示

所用到的包是

from urllib import parse

代码如下

 
  1. from urllib import parse

  2. url='www.xxx.com/?city={}'.format(parse.quote('上海'))

r=requests.get(url)

www.xxx.com/?city=%E4%B8%8A%E6%B5%B7

--------------------- 本文来自 螺纹钢铁侠 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/cc9200/article/details/79999741?utm_source=copy

猜你喜欢

转载自blog.csdn.net/xiaoxianerqq/article/details/82869266
今日推荐