在XML中查找URL的所有页面id

2024-04-20 11:39:30 发布

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

下面是我正在使用的XML备份的结构。我已经编写了一些代码,可以从XML中获取所有URL—有没有一种方法可以为每个URL遍历备份XML并找到它出现的页面ID(下面XML结构中的第二个标记)?你知道吗

<page>
 <id></id>
 <name></name>
 <description>&lt;a href=&quot;http://google.com&quot; target=&quot;_self&quot;&gt;LINK&lt;/a&gt;</description>
 <boxes>
  <box>
  </box>
 </boxes>
</page>

更新:

 <page>
 <id></id>
 <name></name>
 <description></description>
 <url></url>
 <boxes>
  <box>
   <id></id>
   <name></name>
   <type></type>
   <column></column>
   <position></position>
   <hidden></hidden>
   <created></created>
   <updated></updated>
   <assets>
    <asset>
     <id></id>
     <name></name>
     <type></type>
     <description></description>
     <url/>
     <owner>
      <id></id>
      <email></email>
      <first_name></first_name>
      <last_name></last_name>
     </owner>
     <map_id></map_id>
     <position></position>
     <created></created>
     <updated></updated>
    </asset>
   </assets>
  </box>
 </boxes>
</page>

Tags: nameboxidurltypepagepositiondescription
1条回答
网友
1楼 · 发布于 2024-04-20 11:39:30

我通过复制您在问题中提供的内容并输入一些id,创建了一个xml文件。你知道吗

<pages>
    <page>
     <id>1</id>
     <name></name>
     <description>&lt;a href=&quot;http://google.com&quot; target=&quot;_self&quot;&gt;LINK&lt;/a&gt;</description>
     <boxes>
      <box>
      </box>
     </boxes>
    </page>
    <page>
     <id>2</id>
     <name></name>
     <description>&lt;a href=&quot;http://google.com&quot; target=&quot;_self&quot;&gt;LINK&lt;/a&gt;</description>
     <boxes>
      <box>
      </box>
     </boxes>
    </page><page>
     <id>3</id>
     <name></name>
     <description>&lt;a href=&quot;http://google.com&quot; target=&quot;_self&quot;&gt;LINK&lt;/a&gt;</description>
     <boxes>
      <box>
      </box>
     </boxes>
    </page>
</pages>

这段代码显示了ID和描述。你知道吗

>>> from lxml import etree
>>> tree = etree.parse('temp.xml')

>>> for page in tree.xpath('.//page'):
...     page.xpath('id')[0].text, page.xpath('description')[0].text
... 
('1', '<a href="http://google.com" target="_self">LINK</a>')
('2', '<a href="http://google.com" target="_self">LINK</a>')
('3', '<a href="http://google.com" target="_self">LINK</a>')

相关问题 更多 >