Python 파충류 JSON 및 JSONpath 운행 원리 상세 설명

3384 단어 Python파충JSONPath
JSON(JavaScript Object Notation)은 가 벼 운 데이터 교환 형식 으로 사람들 이 쉽게 읽 고 작성 할 수 있 도록 합 니 다.동시에 기계 의 해석 과 생 성 을 편리 하 게 했다.데이터 상호작용 을 하 는 장면,예 를 들 어 사이트 프론트 와 백 스테이지 간 의 데이터 상호작용 에 적용 된다.
JSonPath 는 정보 추출 라 이브 러 리 로 JSON 문서 에서 지정 한 정 보 를 추출 하 는 도구 로 자바 script,Python,PHP 와 자바 등 다양한 언어 구현 버 전 을 제공 합 니 다.
JSonPath 는 JSON 으로 서 는 XPATH 가 XML 에 해당 한다.
JSonPath 와 XPath 문법 비교:
JSon 은 구조 가 뚜렷 하고 가 독성 이 높 으 며 복잡 도가 낮 아 일치 하기 쉬 우 며 다음 표 에서 XPath 의 용법 에 대응 합 니 다.

파 이 썬 관련 강좌
JSONPath 를 이용 하여 인터넷 의 모든 도 시 를 등반 하 다.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
# json   ,   lxml
import json
# json     ,   xpath
import jsonpath
url = "http://www.lagou.com/lbs/getAllCitySearchLabels.json"
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
request = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(request)
#   json      ,         
html = response.read()
#  json         python   Unicode   
unicodestr = json.loads(html)
# Python     
city_list = jsonpath.jsonpath(unicodestr, "$..name")
#for item in city_list:
#  print item
# dumps()     ascii    ,ensure_ascii   Ture
#   ascii    ,   Unicode   ,    
array = json.dumps(city_list, ensure_ascii=False)
#json.dumps(city_list)
#array = json.dumps(city_list)
with open("lagoucity.json", "w") as f:
  f.write(array.encode("utf-8"))
결과:

나 쁜 일 은 백 과 를 기어 서 얻는다.
XPATH 의 모호 한 조 회 를 이용 하여
모든 댓 글 내용 가 져 오기
json 파일 에 저장

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
import json
from lxml import etree
url = "http://www.qiushibaike.com/8hr/page/2/"
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
request = urllib2.Request(url, headers = headers)
html = urllib2.urlopen(request).read()
#          ,   HTML DOM   text = etree.HTML(html)
text = etree.HTML(html)
#            ,contains()      ,            ,             
node_list = text.xpath('//div[contains(@id, "qiushi_tag")]')
items ={}
for node in node_list:
  # xpath     ,          ,        ,   
  username = node.xpath('./div/a/@title')[0]
  #         ,    
  content = node.xpath('.//div[@class="content"]/span')[0].text
  #           ,  
  zan = node.xpath('.//i')[0].text
  #   
  comments = node.xpath('.//i')[1].text
  items = {
    "username" : username,
    "content" : content,
    "zan" : zan,
    "comments" : comments
  }
  with open("qiushi.json", "a") as f:
    f.write(json.dumps(items, ensure_ascii=False).encode("utf-8") + "
")
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기