爬取了下小豬短租的網站出租房信息但是輸出的時候是這種:
百度了下。python2.7在window上的編碼確實是個坑
解決如下
如果是個字典的話要先將其轉成字符串 導入json庫
然后 這么輸出(json.dumps(data).decode("unicode-escape"))
整個代碼demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# -*- 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頁的信息
小結:
壓注意的是
創建soup
1
|
soup = beautifulsoup(html.content) |
多個值的for賦值
1
|
for dizhi,price,em in zip (dizhis,prices,ems): |
字典的輸出編碼問題
1
|
json.dumps(data).decode( "unicode-escape" ) |
如果想獲取每個個詳細信息可以獲取其href屬性值
1
|
#page_list > ul > li:nth-of-type(1) > a |
然后獲取其屬性值get(‘href')獲取每個的詳情信息在解析頁面獲取想要的信息加在data字典中
以上這篇python輸出\u編碼將其轉換成中文的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_28295425/article/details/54799862