Hyp*_*ion 6 python xml parsing
我有这样的站点地图: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>
...
Run Code Online (Sandbox Code Playgroud)
我想从中提取数据.首先,我需要计算有多少<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
Run Code Online (Sandbox Code Playgroud)
但是element_list空的.
我选择使用Requests和BeautifulSoup库.我创建了一个字典,其中键是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
Run Code Online (Sandbox Code Playgroud)
或者使用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
Run Code Online (Sandbox Code Playgroud)
使用 Python 3、请求、Pandas 和列表理解:
import requests
import pandas as pd
import xmltodict
url = "https://www.gov.uk/sitemap.xml"
res = requests.get(url)
raw = xmltodict.parse(res.text)
data = [[r["loc"], r["lastmod"]] for r in raw["sitemapindex"]["sitemap"]]
print("Number of sitemaps:", len(data))
df = pd.DataFrame(data, columns=["links", "lastmod"])
Run Code Online (Sandbox Code Playgroud)
输出:
links lastmod
0 https://www.gov.uk/sitemaps/sitemap_1.xml 2018-11-06T01:10:02+00:00
1 https://www.gov.uk/sitemaps/sitemap_2.xml 2018-11-06T01:10:02+00:00
2 https://www.gov.uk/sitemaps/sitemap_3.xml 2018-11-06T01:10:02+00:00
3 https://www.gov.uk/sitemaps/sitemap_4.xml 2018-11-06T01:10:02+00:00
4 https://www.gov.uk/sitemaps/sitemap_5.xml 2018-11-06T01:10:02+00:00
Run Code Online (Sandbox Code Playgroud)