当前位置: 移动技术网 > IT编程>脚本编程>Python > Python输出u编码将其转换成中文的实例

Python输出u编码将其转换成中文的实例

2019年06月13日  | 移动技术网IT编程  | 我要评论

种田将军沽酒妻,yige,霉霉和水果姐的恩怨

爬取了下小猪短租的网站出租房信息但是输出的时候是这种:

python输出\u编码将其转换成中文

百度了下。python2.7在window上的编码确实是个坑

解决如下

如果是个字典的话要先将其转成字符串 导入json库

然后 这么输出(json.dumps(data).decode("unicode-escape"))

整个代码demo

# -*- coding: utf-8 -*-
#小猪短租爬取
import requests
from bs4 import beautifulsoup
import json
def get_xinxi(i):
 url = 'http://cd.xiaozhu.com/search-duanzufang-p%d-0/' %i
 html = requests.get(url)
 soup = beautifulsoup(html.content)
 #获取地址
 dizhis=soup.select(' div > a > span')
 #获取价格
 prices = soup.select(' span.result_price')
 #获取简单信息
 ems = soup.select(' div > em')
 datas =[]
 for dizhi,price,em in zip(dizhis,prices,ems):
  data={
   '价格':price.get_text(),
   '信息':em.get_text().replace('\n','').replace(' ',''),
   '地址':dizhi.get_text()
  }
  print(json.dumps(data).decode("unicode-escape"))
i=1
while(i<12):
 get_xinxi(i)
 i=i+1

爬取了12页的信息

python输出\u编码将其转换成中文

小结:

压注意的是

创建soup

soup = beautifulsoup(html.content)

多个值的for赋值

for dizhi,price,em in zip(dizhis,prices,ems):

字典的输出编码问题

json.dumps(data).decode("unicode-escape")

如果想获取每个个详细信息可以获取其href属性值

#page_list > ul > li:nth-of-type(1) > a

然后获取其属性值get(‘href')获取每个的详情信息在解析页面获取想要的信息加在data字典中

以上这篇python输出\u编码将其转换成中文的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网