网页json解析 字典内数组

from urllib.request import *
import re
import json
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
import random
import re
import json
import xlrd
import csv

def randHeader():
    head_connection = ['Keep-Alive', 'close']
    head_accept = ['text/html, application/xhtml+xml, */*']
    head_accept_language = ['zh-CN,fr-FR;q=0.5', 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3']
    head_user_agent = ['Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
                       'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko)',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12',
                       'Opera/9.27 (Windows NT 5.2; U; zh-cn)',
                       'Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0',
                       'Opera/8.0 (Macintosh; PPC Mac OS X; U; en)',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6',
                       'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)',
                       'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Maxthon/4.0.6.2000 Chrome/26.0.1410.43 Safari/537.1 ',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; QQBrowser/7.3.9825.400)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 ',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/3.0 Safari/536.11']

    header = {
        'Connection': head_connection[0],
        'Accept': head_accept[0],
        'Accept-Language': head_accept_language[1],
        'User-Agent': head_user_agent[random.randrange(0, len(head_user_agent))]
    }
    return header

def getPartNumber(no):
    url = 'http://catalog.monroe.com/catalogPart/partResults.do?&domain=monroe&locale=en&partNumber='+no+'&selection=findPart'
    # print(url)
    req = urllib.request.Request(url= url , headers=randHeader())
    webpage = urllib.request.urlopen(req)
    html = str(webpage.read())
    html = re.findall("^b'(.*)'", html)[0]
    if html.strip()=="null":
        print("kong")
        return "0"
    s = str(html).replace("\\xae", "")  # 转成str,替换编码174的符号为空
    sjson = re.findall("\[(.*?)\]",s)[0]
    sjson = json.loads(sjson)
    selectedPartId = sjson["value"]
    return selectedPartId

def getTECHandWhereUsed(no):
    # print(no)
    selectedPartId = getPartNumber(no)
    if selectedPartId== "0":
        file2 = open("tech_specs.csv", "a", newline="")
        writer = csv.writer(file2)
        writer.writerow([no, "#",  "#" ,"#", "#" ,"#" ,"#", "#" ,"#" ,"#", "#" ])
        file1 = open("where_used.csv", "a", newline="")
        writer1 = csv.writer(file1)
        writer1.writerow([no, "#"])
        return
    url = "http://catalog.monroe.com/catalogPart/partResults.do?&selectedCatalogId=974&selectedPartId="+str(selectedPartId)+"&selection=partDetails"
    req = urllib.request.Request(url= url , headers=randHeader())
    webpage = urllib.request.urlopen(req)
    html = webpage.read() #  字节编码
    s = str(html).replace("\\xae","") #转成str,替换编码174的符号为空
    s = re.findall("^b'(.*)'", s)[0]
    s = s.replace("\\\\","\\")  #将\\转换成\
    s = s.replace("\\'" , "'")#将\'转换成'
    s = json.loads(s )
    att = s["part"]["attributes"] #定位属性
    for i in att:
        for key , value in i.items(): #选择指定的属性
            key = str(key)
            if key == "Body Type":
                bType = value
            elif key == "Body Length":
                bLength = value
            elif key == "Compressed Length":
                cLength = value
            elif key == "Extended Length":
                eLength = value
            elif key == "Travel Length":
                tlength = value
            elif key == "Dust Shield":
                dShield = value
            elif key == "Parts Pack(s)":
                ppack = value
            elif key == "Compressed Bumper Stop":
                cBStop = value
            elif key == "Extended Bumper Stop":
                ebStop = value
            elif key == "Extended Hydraulic Lockout":
                ehLockout = value
    # print(bType, bLength,  cLength , eLength , tlength , dShield , ppack , cBStop , ebStop , ehLockout)
    file2 = open("tech_specs.csv","a" , newline="")
    writer = csv.writer(file2)
    writer.writerow([no , bType, bLength,  cLength , eLength , tlength , dShield , ppack , cBStop , ebStop , ehLockout])
    result = []
    ve = s["vehicles"] #定位车型
    for i in ve:
        make = i["make"]
        modle = i["models"]
        for i in modle :
            model = i["model"]
            app = i["applications"]
            for i in app:
                location = i["location"]
                startYear = i["startYear"]
                endYear = i["endYear"]
                fitment = str(startYear)+" - "+ str(endYear) + " "+ str(location).upper()
                result.append([make , model , fitment])
    # print(result)
    file1 = open("where_used.csv","a",newline="")
    writer1 = csv.writer(file1)
    for fitment in result:
        writer1.writerow([no , fitment])



#读入no
data  = xlrd.open_workbook("no.xlsx") #代开excel
table = data.sheet_by_name("Sheet1") #读sheet
nrows = table.nrows
cols = table.ncols
nos = []
for i in range(1,nrows):  #指定从1开始,到最后一列,跳过表头
    for j in range(cols):
        ctype = table.cell(i , j).ctype #判断python读取的返回类型  0 --empty,1 --string, 2 --number(都是浮点), 3 --date, 4 --boolean, 5 --error
        no = table.cell(i, j).value #获取单元格的值
        if ctype == 2 :
            no = str(int(no)) #将浮点转换成整数再转换成字符串
        nos.append(no)

#写入csv表头
with open("tech_specs.csv","a",newline="") as f:
    head = ["no","bType", "bLength",  "cLength" , "eLength" , "tlength" , "dShield" , "ppack" , "cBStop" , "ebStop" , "ehLockout"]
    writer =csv.DictWriter(f, fieldnames=head)
    writer.writeheader()
with open("where_used.csv","a" , newline="") as wf :
    head= ["no", "fitment"]
    writer2 = csv.DictWriter(wf , fieldnames= head)
    writer2.writeheader()
for no in nos:
    print(no)
    getTECHandWhereUsed(no)


# getTECHandWhereUsed("171340R")


python 代码中有的正则表达式消失的需要参考上面修改

from urllib.request import *
import re
import json
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
import random
import re
import json
import xlrd
import csv

def randHeader():
    head_connection = ['Keep-Alive', 'close']
    head_accept = ['text/html, application/xhtml+xml, */*']
    head_accept_language = ['zh-CN,fr-FR;q=0.5', 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3']
    head_user_agent = ['Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
                       'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko)',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12',
                       'Opera/9.27 (Windows NT 5.2; U; zh-cn)',
                       'Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0',
                       'Opera/8.0 (Macintosh; PPC Mac OS X; U; en)',
                       'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6',
                       'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)',
                       'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Maxthon/4.0.6.2000 Chrome/26.0.1410.43 Safari/537.1 ',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; QQBrowser/7.3.9825.400)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 ',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER',
                       'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/3.0 Safari/536.11']

    header = {
        'Connection': head_connection[0],
        'Accept': head_accept[0],
        'Accept-Language': head_accept_language[1],
        'User-Agent': head_user_agent[random.randrange(0, len(head_user_agent))]
    }
    return header

def getPartNumber(no):
    url = 'http://catalog.monroe.com/catalogPart/partResults.do?&domain=monroe&locale=en&partNumber='+no+'&selection=findPart'
    # print(url)
    req = urllib.request.Request(url= url , headers=randHeader())
    webpage = urllib.request.urlopen(req)
    html = str(webpage.read())
    html = re.findall("^b'(.*)'", html)[0]
    if html.strip()=="null":
        print("kong")
        return "0"
    s = str(html).replace("\\xae", "")  # 转成str,替换编码174的符号为空
    sjson = re.findall("\[(.*?)\]",s)[0]
    sjson = json.loads(sjson)
    selectedPartId = sjson["value"]
    return selectedPartId

def getTECHandWhereUsed(no):
    # print(no)
    selectedPartId = getPartNumber(no)
    if selectedPartId== "0":
        file2 = open("tech_specs.csv", "a", newline="")
        writer = csv.writer(file2)
        writer.writerow([no, "#",  "#" ,"#", "#" ,"#" ,"#", "#" ,"#" ,"#", "#" ])
        file1 = open("where_used.csv", "a", newline="")
        writer1 = csv.writer(file1)
        writer1.writerow([no, "#"])
        return
    url = "http://catalog.monroe.com/catalogPart/partResults.do?&selectedCatalogId=974&selectedPartId="+str(selectedPartId)+"&selection=partDetails"
    req = urllib.request.Request(url= url , headers=randHeader())
    webpage = urllib.request.urlopen(req)
    html = webpage.read() #  字节编码
    s = str(html).replace("\\xae","") #转成str,替换编码174的符号为空
    s = re.findall("^b'(.*)'", s)[0]
    s = s.replace("\\\\","\\")  #将\\转换成\
    s = s.replace("\\'" , "'")#将\'转换成'
    s = json.loads(s )
    att = s["part"]["attributes"] #定位属性
    for i in att:
        for key , value in i.items(): #选择指定的属性
            key = str(key)
            if key == "Body Type":
                bType = value
            elif key == "Body Length":
                bLength = value
            elif key == "Compressed Length":
                cLength = value
            elif key == "Extended Length":
                eLength = value
            elif key == "Travel Length":
                tlength = value
            elif key == "Dust Shield":
                dShield = value
            elif key == "Parts Pack(s)":
                ppack = value
            elif key == "Compressed Bumper Stop":
                cBStop = value
            elif key == "Extended Bumper Stop":
                ebStop = value
            elif key == "Extended Hydraulic Lockout":
                ehLockout = value
    # print(bType, bLength,  cLength , eLength , tlength , dShield , ppack , cBStop , ebStop , ehLockout)
    file2 = open("tech_specs.csv","a" , newline="")
    writer = csv.writer(file2)
    writer.writerow([no , bType, bLength,  cLength , eLength , tlength , dShield , ppack , cBStop , ebStop , ehLockout])
    result = []
    ve = s["vehicles"] #定位车型
    for i in ve:
        make = i["make"]
        modle = i["models"]
        for i in modle :
            model = i["model"]
            app = i["applications"]
            for i in app:
                location = i["location"]
                startYear = i["startYear"]
                endYear = i["endYear"]
                fitment = str(startYear)+" - "+ str(endYear) + " "+ str(location).upper()
                result.append([make , model , fitment])
    # print(result)
    file1 = open("where_used.csv","a",newline="")
    writer1 = csv.writer(file1)
    for fitment in result:
        writer1.writerow([no , fitment])



#读入no
data  = xlrd.open_workbook("no.xlsx") #代开excel
table = data.sheet_by_name("Sheet1") #读sheet
nrows = table.nrows
cols = table.ncols
nos = []
for i in range(1,nrows):  #指定从1开始,到最后一列,跳过表头
    for j in range(cols):
        ctype = table.cell(i , j).ctype #判断python读取的返回类型  0 --empty,1 --string, 2 --number(都是浮点), 3 --date, 4 --boolean, 5 --error
        no = table.cell(i, j).value #获取单元格的值
        if ctype == 2 :
            no = str(int(no)) #将浮点转换成整数再转换成字符串
        nos.append(no)

#写入csv表头
with open("tech_specs.csv","a",newline="") as f:
    head = ["no","bType", "bLength",  "cLength" , "eLength" , "tlength" , "dShield" , "ppack" , "cBStop" , "ebStop" , "ehLockout"]
    writer =csv.DictWriter(f, fieldnames=head)
    writer.writeheader()
with open("where_used.csv","a" , newline="") as wf :
    head= ["no", "fitment"]
    writer2 = csv.DictWriter(wf , fieldnames= head)
    writer2.writeheader()
for no in nos:
    print(no)
    getTECHandWhereUsed(no)


# getTECHandWhereUsed("171340R")




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值