首页 > 解决方案 > 尝试将站点分别抓取到 xml 和 json 时未找到元素/期望值

问题描述

我一直在尝试解析网站一段时间,但在尝试解析网站时不断出错。当我尝试使用 XML 时,我得到了这个:

xml.etree.ElementTree.ParseError:找不到元素:第 1 行,第 1 列

当我尝试使用 json 时,我得到了这个:

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

我的 xml 代码是:

import urllib.request, urllib.parse, urllib.error
import ssl
import xml.etree.ElementTree as PT

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:

 url= input('Enter Location: ')
 print('Retrieving', url)

 uh = urllib.request.urlopen(url, context=ctx)
 data = uh.read()
 print('Retrieved', len(data), 'characters')

 tree=PT.fromstring (uh.read())

 print (tree)
 break

我的 json 代码是:

import urllib.request, urllib.parse, urllib.error
import ssl
import json
import requests

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:

 url= input('Enter Location: ')
 print('Retrieving', url)

 r = requests.get(url, auth=('user', 'pass'))

 m=r.json()

 print (m)
 break

标签: pythonjsonxmlweb-scraping

解决方案


推荐阅读