Beautiful Soup:只解析一个元素
Beautiful Soup: Parsing only one element
我一直 运行 靠墙,但感觉我离这里很近。
HTML 正在收获的区块:
div class="details">
<div class="price">
<h3>From</h3>
<strike data-round="true" data-currency="USD" data-price="148.00" title="US8 ">€136</strike>
<span data-round="true" data-currency="USD" data-price="136.00" title="US6 ">€125</span>
</div>
我想单独解析出 "US6" 值(跨度数据)。到目前为止,这是我的逻辑,它捕获了 'span data' 和 'strike-data:
price = item.find_all("div", {"class": "price"})
price_final = (price[0].text.strip()[8:])
print(price_final)
欢迎任何反馈:)
price
在您的例子中是一个 ResultSet
- div
标签的列表具有 price
class。现在您需要在每个结果中找到一个 span
标签(假设您要匹配多个价格):
prices = item.find_all("div", {"class": "price"})
for price in prices:
price_final = price.span.text.strip()
print(price_final)
如果只有一次价格需要查找:
soup.find("div", {"class": "price"}).span.get_text()
或 CSS selector:
soup.select_one("div.details div.price span").get_text()
请注意,如果您想使用 select_one()
,请安装最新的 beautifulsoup4
软件包:
pip install --upgrade beautifulsoup4
我一直 运行 靠墙,但感觉我离这里很近。
HTML 正在收获的区块:
div class="details">
<div class="price">
<h3>From</h3>
<strike data-round="true" data-currency="USD" data-price="148.00" title="US8 ">€136</strike>
<span data-round="true" data-currency="USD" data-price="136.00" title="US6 ">€125</span>
</div>
我想单独解析出 "US6" 值(跨度数据)。到目前为止,这是我的逻辑,它捕获了 'span data' 和 'strike-data:
price = item.find_all("div", {"class": "price"})
price_final = (price[0].text.strip()[8:])
print(price_final)
欢迎任何反馈:)
price
在您的例子中是一个 ResultSet
- div
标签的列表具有 price
class。现在您需要在每个结果中找到一个 span
标签(假设您要匹配多个价格):
prices = item.find_all("div", {"class": "price"})
for price in prices:
price_final = price.span.text.strip()
print(price_final)
如果只有一次价格需要查找:
soup.find("div", {"class": "price"}).span.get_text()
或 CSS selector:
soup.select_one("div.details div.price span").get_text()
请注意,如果您想使用 select_one()
,请安装最新的 beautifulsoup4
软件包:
pip install --upgrade beautifulsoup4