Home Backend Development Python Tutorial Crawler parsing method 1: JOSN parsing

Crawler parsing method 1: JOSN parsing

Jun 05, 2019 am 11:14 AM
python reptile

Many languages ​​​​can crawl, but crawlers based on python are more concise and convenient. Crawlers have also become an essential part of the python language. There are many ways for crawlers to parse data. In the previous article, I introduced to you what kind of data the crawler can obtain and the specific parsing methods. ,This This article brings you JSON parsing.

Crawler parsing method 1: JOSN parsing

JSON

Json is simply an object and an array in JavaScript, so these two structures are objects and arrays. Structure, through these two structures various complex structures can be represented.

Object:

The object is represented in js as the content enclosed by { }, and the data structure is { key: value, key: value, ... } The structure of key-value pairs. In object-oriented languages, key is the attribute of the object, and value is the corresponding attribute value, so it is easy to understand. The value method is object.key to obtain the attribute value. The type of this attribute value can be a number. , strings, arrays, objects.

Array:

The array in js is the content enclosed by square brackets [ ], and the data structure is ["Python", "javascript", "C ", ...], the value acquisition method is the same as in all languages, using index to obtain, the type of field value can be numbers, strings, arrays, objects.

JSON (JavaScript Object Notation) is a lightweight data exchange format that makes it easy for people to read and write. It also facilitates machine analysis and generation. Suitable for data interaction scenarios, such as data interaction between the front and backend of a website.

import json
def resolveJson(path):
    file = open(path, "rb")
    fileJson = json.load(file)
    field = fileJson["field"]
    futures = fileJson["futures"]
    type = fileJson["type"]
    name = fileJson["name"]
    time = fileJson["time"]
    return (field, futures, type, name, time)
def output():
    result = resolveJson(path)
    print(result)
    for x in result:
        for y in x:
            print(y)
path = r"C:\Users\dell\Desktop\kt\test.json"
output()
Copy after login

Note that when the function returns multiple values, it returns a tuple;

When performing a for loop on a string, each character will be traversed

Python JSON

In this chapter we will introduce how to use Python language to encode and decode JSON objects.

JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy for humans to read and write.


JSON function

Using the JSON function requires importing the json library: import json.

Function                                                                                                                                                                                                                                     Encoded JSON string decoded into Python object

json.dumps

##json.dumps Used to encode Python objects into JSON strings.

Syntax

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators =None, encoding="utf-8", default=None, sort_keys=False, **kw)

Example

The following example encodes the array into JSON format Data:

#!/usr/bin/python
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = json.dumps(data)
print json
Copy after login

The execution result of the above code is:

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
Copy after login
Use parameters to format JSON data for output:

>>> import json
>>> print json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
    "a": "Runoob",
    "b": 7
}
Copy after login

Conversion control of python original type to json type Table:

Python

#list, tuple                                     array

str, unicode                                                     ’s

int, long, float                                                                                                                                                   false

None null

json.loads

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Copy after login

实例

以下实例展示了Python 如何解码 JSON 对象:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import json
jsonData = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
text = json.loads(jsonData)
print text
Copy after login

以上代码执行结果为:

{u&#39;a&#39;: 1, u&#39;c&#39;: 3, u&#39;b&#39;: 2, u&#39;e&#39;: 5, u&#39;d&#39;: 4}
Copy after login
Copy after login

json 类型转换到 python 的类型对照表:

JSON Python

object dict

array list

string unicode

number (int) int, long

number (real) float

true True

false False

null None

使用第三方库:Demjson

Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。

Github 地址:https://github.com/dmeranda/demjson

官方地址:http://deron.meranda.us/python/demjson/

环境配置

在使用 Demjson 编码或解码 JSON 数据前,我们需要先安装 Demjson 模块。本教程我们会下载 Demjson 并安装:

$ tar -xvzf demjson-2.2.3.tar.gz
$ cd demjson-2.2.3
$ python setup.py install
Copy after login

JSON 函数

函数 描述

encode 将 Python 对象编码成 JSON 字符串

decode 将已编码的 JSON 字符串解码为 Python 对象

encode

Python encode() 函数用于将 Python 对象编码成 JSON 字符串。

语法

demjson.encode(self, obj, nest_level=0)


实例

以下实例将数组编码为 JSON 格式数据:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import demjson
data = [ { &#39;a&#39; : 1, &#39;b&#39; : 2, &#39;c&#39; : 3, &#39;d&#39; : 4, &#39;e&#39; : 5 } ]
json = demjson.encode(data)
print json
Copy after login

以上代码执行结果为:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Copy after login


decode

Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

demjson.decode(self, txt)

实例

以下实例展示了Python 如何解码 JSON 对象:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import demjson
json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
text = demjson.decode(json)
print  text
Copy after login

以上代码执行结果为:

{u&#39;a&#39;: 1, u&#39;c&#39;: 3, u&#39;b&#39;: 2, u&#39;e&#39;: 5, u&#39;d&#39;: 4}
Copy after login
Copy after login

The above is the detailed content of Crawler parsing method 1: JOSN parsing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles