繁体   English   中英

Python,从包含某个单词的xml站点地图中提取url

[英]Python, extract urls from xml sitemap that contain a certain word

我正在尝试从 URL 中包含单词 foo 的站点地图中提取所有 URL。 我设法提取了所有网址,但不知道如何只获取我想要的网址。 所以在下面的例子中,我只想要返回苹果和梨的网址。

<url>
<loc>
https://www.example.com/p-1224-apples-foo-09897.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>
https://www.example.com/p-1433-pears-foo-00077.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>
https://www.example.com/p-3411-oranges-ping-66554.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>

我将 xml 修改为有效格式(添加<urls></urls> ),将它们保存到 src.xml 中:

<urls>
<url>
<loc>
https://www.example.com/p-1224-apples-foo-09897.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>
https://www.example.com/p-1433-pears-foo-00077.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>
https://www.example.com/p-3411-oranges-ping-66554.php
</loc>
<lastmod>2018-05-29</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
</urls>

使用xml.etree.ElementTree解析 xml:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('src.xml')
>>> root = tree.getroot()
>>> for url in root.findall('url'):
...     for loc in url.findall('loc'):
...             if loc.text.__contains__('foo'):
...                     print(loc.text)
...

https://www.example.com/p-1224-apples-foo-09897.php
https://www.example.com/p-1433-pears-foo-00077.php

假设它们总是在loc标记的元素中,那么您可以使用 XPath 方法

//loc[contains(text(),'foo')]

通用将是:

//*[contains(text(),'foo')]

它需要使用支持 XPath 的lxml ,请参见此处。

如果您拥有所有网址,那么您可以使用in检查每个网址中是否包含“foo”一词。 像这样的东西(假设您已经拥有名为urls的列表中的所有urls ):

urls = [url for url in urls if 'foo' in url]
from xml.dom.minidom import parse
import xml.dom.minidom
xml_file = r'your_file.xml'
DOMTree = xml.dom.minidom.parse(xml_file)
root_node = DOMTree.documentElement
print(root_node.nodeName)
loc_nodes = root_node.getElementsByTagName("loc")
for loc in loc_nodes:
    print(loc.childNodes[0].data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM