如何从xml文件中提取链接并将其作为文本文件保存在python文件所在的文件夹中

2024-06-26 00:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图提取到一个文本文件的链接在xml中有多个链接

<url>
<loc>http://www.something.it/en/new</loc>
    <changefreq>daily</changefreq>
        <lastmod>2018-01-21</lastmod>
            <priority>0.7</priority>
</url>


from bs4 import BeautifulSoup

xml1 = req.get("https://www.something.it/sitemap.xml")
content = xml1.text
stripped = re.sub('<[^<]+?>', content)

print (stripped)

我得到这个作为输出在终端,我只需要链接,其他什么都不需要,并保存为文件.text在包含python文件的同一个文件夹中

http://www.something.it/en/latest 每日的 2018年1月21日 0.7


Tags: texthttpurl链接wwwitxmlcontent
1条回答
网友
1楼 · 发布于 2024-06-26 00:13:52

您可以使用xml(ElementTree)单独提取url:

例如:

import xml.etree.ElementTree as ET

#content = xml1.text    
content = """<url>
<loc>http://www.something.it/en/new</loc>
    <changefreq>daily</changefreq>
        <lastmod>2018-01-21</lastmod>
            <priority>0.7</priority>
</url>"""


xmlContent = ET.fromstring(content)
for content in xmlContent.findall('.//loc'):
    print content.text

结果:

^{pr2}$

相关问题 更多 >