Python 파충류 JSON 및 JSONpath 운행 원리 상세 설명
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") + "
")
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.