gpt4 book ai didi

python - 使用 Python 解析 XML 站点地图

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:22 26 4
gpt4 key购买 nike

我有这样的站点地图:http://www.site.co.uk/sitemap.xml其结构如下:

<sitemapindex>
<sitemap>
<loc>
http://www.site.co.uk/drag_it/dragitsitemap_static_0.xml
</loc>
<lastmod>2015-07-07</lastmod>
</sitemap>
<sitemap>
<loc>
http://www.site.co.uk/drag_it/dragitsitemap_alpha_0.xml
</loc>
<lastmod>2015-07-07</lastmod>
</sitemap>
...

我想从中提取数据。首先我需要数一数有多少 <sitemap>在 xml 中,然后为它们中的每一个提取 <loc><lastmod>数据。有没有一种简单的方法可以在 Python 中执行此操作?

我见过其他类似的问题,但它们都提取了例如每个 <loc> xml 中的元素,我需要从每个元素中单独提取数据。

我试过使用 lxml使用此代码:

import urllib2
from lxml import etree

u = urllib2.urlopen('http://www.site.co.uk/sitemap.xml')
doc = etree.parse(u)

element_list = doc.findall('sitemap')

for element in element_list:
url = store.findtext('loc')
print url

但是element_list是空的。

最佳答案

我选择使用 RequestsBeautifulSoup图书馆。我创建了一个字典,其中键是 url,值是最后修改日期。

from bs4 import BeautifulSoup
import requests

xmlDict = {}

r = requests.get("http://www.site.co.uk/sitemap.xml")
xml = r.text

soup = BeautifulSoup(xml)
sitemapTags = soup.find_all("sitemap")

print "The number of sitemaps are {0}".format(len(sitemapTags))

for sitemap in sitemapTags:
xmlDict[sitemap.findNext("loc").text] = sitemap.findNext("lastmod").text

print xmlDict

或用lxml :

from lxml import etree
import requests

xmlDict = {}

r = requests.get("http://www.site.co.uk/sitemap.xml")
root = etree.fromstring(r.content)
print "The number of sitemap tags are {0}".format(len(root))
for sitemap in root:
children = sitemap.getchildren()
xmlDict[children[0].text] = children[1].text
print xmlDict

关于python - 使用 Python 解析 XML 站点地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com