下面是我要解析的 xml。
<url>
<loc>https://www.houseofindya.com/aqua-chanderi-pleated-sharara-pants-177/iprdt</loc>
<image:image>
<image:loc>https://img.faballey.com/Images/Product/IPL00325Z/d3.jpg</image:loc>
<image:title>Green Chanderi Pleated Sharara Pants</image:title>
</image:image>
<priority>0.8</priority>
<changefreq>daily</changefreq>
</url>
<url>
<loc>https://www.houseofindya.com/aqua-foil-chanderi-kurta-171/iprdt</loc>
<image:image>
<image:loc>https://img.faballey.com/Images/Product/ITN01710Z/d3.jpg</image:loc>
<image:title>Aqua Foil Chanderi Kurta</image:title>
</image:image>
<priority>0.8</priority>
<changefreq>daily</changefreq>
</url>
我只需要获取 <loc>
标签的文本。因此,我执行以下操作:-
soup = BeautifulSoup(xml, features='xml')
loc = soup.find('loc')
while loc is not None:
url = loc.text
yield url
loc = loc.find_next('loc')
我得到的结果是
https://www.houseofindya.com/aqua-chanderi-pleated-sharara-pants-177/iprdt
https://img.faballey.com/Images/Product/IPL00325Z/d3.jpg
https://www.houseofindya.com/aqua-foil-chanderi-kurta-171/iprdt
https://img.faballey.com/Images/Product/ITN01710Z/d3.jpg
但是,我想要的只是 https://www.houseofindya.com/aqua-chanderi-pleated-sharara-pants-177/iprdt
和 https://www.houseofindya.com/aqua-foil-chanderi-kurta-171/iprdt
。我不想要 <image:loc>
的文本。
我在这里想念什么?
回答1
您甚至可以在 XML 文档中使用 CSS
选择器,因此选择所有 url > loc
:
from bs4 import BeautifulSoup
xml_doc = """
... your XML from question here ...
"""
soup = BeautifulSoup(xml_doc, "html.parser")
for loc in soup.select("url > loc"):
print(loc.text)
印刷:
https://www.houseofindya.com/aqua-chanderi-pleated-sharara-pants-177/iprdt
https://www.houseofindya.com/aqua-foil-chanderi-kurta-171/iprdt