Beautiful Soup:只解析一个元素

Ser*_*ffy 5 html python parsing beautifulsoup html-parsing

我一直在撞墙,但感觉我离这里很近了。

正在收获的 HTML 块:

div class="details">
   <div class="price">
   <h3>From</h3>
   <strike data-round="true" data-currency="USD" data-price="148.00" title="US$148 ">€136</strike>
   <span data-round="true" data-currency="USD" data-price="136.00" title="US$136 ">€125</span>
</div>
Run Code Online (Sandbox Code Playgroud)

我想单独解析出“136 美元”的值(跨度数据)。到目前为止,这是我的逻辑,它同时捕获了“跨度数据”和“罢工数据”:

price = item.find_all("div", {"class": "price"})
        price_final = (price[0].text.strip()[8:])
        print(price_final)
Run Code Online (Sandbox Code Playgroud)

任何反馈表示赞赏:)

ale*_*cxe 5

price在您的情况下是ResultSet-div具有price类的标签列表。现在您需要span在每个结果中找到一个标签(假设您要匹配多个价格):

prices = item.find_all("div", {"class": "price"})
for price in prices:
    price_final = price.span.text.strip()
    print(price_final)
Run Code Online (Sandbox Code Playgroud)

如果只有一次价格,您需要找到:

soup.find("div", {"class": "price"}).span.get_text()
Run Code Online (Sandbox Code Playgroud)

或使用CSS 选择器

soup.select_one("div.details div.price span").get_text()
Run Code Online (Sandbox Code Playgroud)

请注意,如果要使用select_one(),请安装最新的beautifulsoup4软件包:

pip install --upgrade beautifulsoup4
Run Code Online (Sandbox Code Playgroud)