【问题标题】:Python, extract urls from xml sitemap that contain a certain wordPython,从包含某个单词的 xml 站点地图中提取 url
【发布时间】:2019-03-05 16:59:20
【问题描述】:
我正在尝试从站点地图中提取 URL 中包含单词 foo 的所有 URL。我已经设法提取了所有的 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>
【问题讨论】:
标签:
python
xml
web-scraping
beautifulsoup
【解决方案1】:
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)
【解决方案2】:
如果您拥有所有网址,则可以使用in 检查每个网址中是否包含“foo”一词。像这样的东西(假设您已经在名为urls 的列表中拥有所有网址):
urls = [url for url in urls if 'foo' in url]
【解决方案3】:
我将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
【解决方案4】:
假设它们总是在元素中 loc 标记,那么您可以使用 XPath 方法
//loc[contains(text(),'foo')]
一般是:
//*[contains(text(),'foo')]
需要使用支持XPath的lxml,见here.