首页 > 解决方案 > 如何在 BeautifulSoup 中使用 find() 和 find_all()?

问题描述

我目前正在做一些网络抓取。我有这个 HTML:

<meta property="og:price:amount" content="1.89"/>
<meta property="og:price:standard_amount" content="6.31"/>
<meta property="og:price:currency" content="USD"/>

我正在使用美丽的汤(Python)。

我要提取的信息是 1.89 和 6.31(产品价格)。

这是我的代码:

import requests
from bs4 import BeautifulSoup


page = requests.get('https://spanish.alibaba.com/product-detail/crazy-hot-selling-multifunctional-battery-powered-360-degree-rotation-led-light-makeup-mirror-60769168637.html?spm=a2700.8270666-66.2016122619262.17.5a4d5d09En8wm9')

# Create a BeautifulSoup object
soup = BeautifulSoup(page.text, 'html.parser')
#print(soup.get_text())
# get the repo list


v2 = soup.find_all("meta", {"property": "og:price:amount", "content": True}['content'] )
print("v2 is",v2)

错误在.find_all()函数中,我不确定如何提取数据。我也试过这个.find()功能

这是我得到的关于美丽汤功能如何工作的信息: Signature: find_all(name, attrs, recursive, string, limit, **kwargs)

帮我配置一下 .find()功能。谢谢!

标签: pythonweb-scrapingbeautifulsoup

解决方案


而不是find_all()仅仅使用find()

find_all()返回元素列表。

v2 = soup.find("meta", {"property": "og:price:amount", "content": True})['content'] 
print("v2 is",v2)

或者您可以使用Css 选择器

v2 = soup.select_one('meta[property="og:price:amount"][content]')['content']
print("v2 is",v2)

推荐阅读