python - 在 Python 中读取 gz/gzip XML Sitemap
问题描述
我尝试将 gzipped XML 站点地图读取到 pandas。请求应该能够自动处理 gzip,并且在标头中检测到 gzip,但是 gzip 无法正常工作,显示“格式不正确(无效令牌):第 1 行,第 0 列”,但站点地图对我来说看起来不错?
import requests
import pandas as pd
import xmltodict
import numpy as np
url = "https://www.blick.ch/article.xml"
res = requests.get(url)
raw = xmltodict.parse(res.text)
dfAllLocs = pd.DataFrame({'loc': []})
for r in raw["sitemapindex"]["sitemap"]:
#try:
print(r["loc"])
resSingle = requests.get(r["loc"])
#print(resSingle.headers)
rawSingle = xmltodict.parse(resSingle.text, encoding='utf-8')
dataSingle = [[rSingle["loc"]] for rSingle in rawSingle["urlset"]["url"]]
dfSingle = pd.DataFrame(dataSingle, columns=["loc"])
dfAllLocs = pd.concat([dfAllLocs,dfSingle])
print(len(dfAllLocs))
#except:
# print("something went wrong at: " + r["loc"])
解决方案
谢谢 Ionut Ticus。这个链接非常有用无法获取请求==2.7.0 以自动解压缩 gzip
现在工作
#Get Sitemap
url = 'https://www.watson.ch/sitemap.xml'
pattern = '(.*?)\/'
maxSubsitemapsToCrawl = 10
res = requests.get(url)
raw = xmltodict.parse(res.text)
dfSitemap = pd.DataFrame({'loc': []})
breakcounter = 0
for r in raw["sitemapindex"]["sitemap"]:
try:
print(r["loc"])
resSingle = requests.get(r["loc"], stream=True)
if resSingle.status_code == 200:
if resSingle.headers['Content-Type'] == 'application/x-gzip':
resSingle.raw.decode_content = True
resSingle = gzip.GzipFile(fileobj=resSingle.raw)
else:
resSingle = resSingle.text
rawSingle = xmltodict.parse(resSingle)
dataSingle = [[rSingle["loc"]] for rSingle in rawSingle["urlset"]["url"]]
dfSingle = pd.DataFrame(dataSingle, columns=["loc"])
dfSitemap = pd.concat([dfSitemap,dfSingle])
print(len(dfSitemap))
except:
print("something went wrong at: " + r["loc"])
breakcounter += 1
if breakcounter == maxSubsitemapsToCrawl:
break
推荐阅读
- python - 用于获取信息的 Vsphere API 脚本
- mysql - 我们可以在连接表时在连接条件中使用 Case When created 列吗
- javascript - 当我启动我的 React-Native 应用程序时如何修复我的错误?
- c++ - 保持 boost::allocators 作为类成员。可以使用它们来初始化容器
- html - 引导模式未显示在操作中
- standardjs - 找不到模块“babel-eslint”(标准和 babel-eslint 已在本地安装)
- delphi - 如何获取 TPersistentClass 来自的动态包?
- c++ - 反转字符串?更优化的方式
- xml - 行错误:76 col:82 Line:76 ';' 预期,得到 char[61]
- push - ejabberd mod_push 和 mod_push_keepalive 不启动