我想在following example中找到所有价格为8.99的图书的书名。换句话说,我想根据同级元素的文本查找元素的文本。
from bs4 import BeautifulSoup
XML = """<?xml version="1.0">
<library>
<book>
<title>The Cat in the Hat</title>
<author>Dr. Seuss</author>
<price>7.35</price>
</book>
<book>
<title>Ender's Game</title>
<author>Orson Scott Card</author>
<price>8.99</price>
</book>
<book>
<title>Prey</title>
<author>Michael Crichton</author>
<price>8.99</price>
</book>
</library>
"""
soup = BeautifulSoup(XML, "xml")
令人惊讶的是,查询soup.find({"price": 8.99}).parent
将返回错误的书:
<book>
<title>The Cat in the Hat</title>
<author>Dr. Seuss</author>
<price>7.35</price>
</book>
更新
查询[x.parent.find("title").text for x in soup.find_all("price", text = 8.99)]
返回列表["Ender's Game", "Prey"]
,这正是我想要的。但这是最好的方法吗?
答案 0 :(得分:0)
您可以使用find_previous_sibling()
。
from bs4 import BeautifulSoup
XML = """<?xml version="1.0">
<library>
<book>
<title>The Cat in the Hat</title>
<author>Dr. Seuss</author>
<price>7.35</price>
</book>
<book>
<title>Ender's Game</title>
<author>Orson Scott Card</author>
<price>8.99</price>
</book>
<book>
<title>Prey</title>
<author>Michael Crichton</author>
<price>8.99</price>
</book>
</library>
"""
soup = BeautifulSoup(XML, "xml")
prices = soup.find_all("price", text=8.99)
for price in prices:
title = price.find_previous_sibling('title')
print(title)
# and with list comprehension
titles = [price.find_previous_sibling('title').text for price in prices]
print(titles)
输出
<title>Ender's Game</title>
<title>Prey</title>
# List comprehension
["Ender's Game", 'Prey']