[python爬虫]把js转化成json

有一个优秀的库可以使用demjson

示范链接
http://fcd.5173.com/commondat...

TIM截图20191112185355.png

如果我们要把这个变成字典,需要先把他转成json,再从json变成dict

通过demjson可以一步到位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests
import demjson

url = 'http://fcd.5173.com/commondata/Category.aspx?type=area&cache=&id=20c8bbc1b9794fc98bd96859624d4769&jsoncallback=callarea'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
}

resposne = requests.get(url, headers=headers)

for item in demjson.decode(resposne.text[9:-1]):
    id = item.get('id')
    name = item.get('name')
    print(id, name)

得到如下结果
2.png

直接通过json.loads是行不通的

1
2
3
4
5
6
7
8
9
10
11
12
import requests
import json

url = 'http://fcd.5173.com/commondata/Category.aspx?type=area&cache=&id=20c8bbc1b9794fc98bd96859624d4769&jsoncallback=callarea'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
}

resposne = requests.get(url, headers=headers)

print(json.loads(resposne.text[9:-1]))

3.png