首页 > 解决方案 > 在 Python3 中使用 BeautifulSoup4 刮价格 Udemy 网站

问题描述

我正在尝试从 Udemy 网站提取价格数据以及学生人数。我在 Windows 上,我在 conda 环境中使用 Python 3.8 和 BeautifoulSoup。

这是我的代码:

url = 'https://www.udemy.com/course/business-analysis-conduct-a-strategy-analysis/'
html = requests.get(url).content
bs = BeautifulSoup(html, 'lxml')
searchingprice = bs.find('div', {'class':'price-text--price-part--2npPm udlite-clp-discount-price udlite-heading-xxl','data-purpose':'course-price-text'})
searchingstudents = bs.find('div', {'class':'','data-purpose':'enrollment'})
print(searchingprice)
print(searchingstudents)

而且我只得到有关学生的信息,而不是价格。我做错了什么?

None
<div class="" data-purpose="enrollment">
13,490 students
</div>

这是关于该网站的屏幕截图: 价格

学生

谢谢!

标签: pythonpython-3.xweb-scrapingbeautifulsoup

解决方案


价格不在源代码中,它是用 javascript 获取的。我们必须采取同样的步骤。这段代码是你自己的,bs 已经加载了

# get id of the course
course_id=bs.body.attrs['data-clp-course-id']
# build proper request, feel free to delete unneeded data requests
link=f'https://www.udemy.com/api-2.0/pricing/?course_ids={course_id}&fields[pricing_result]=price,discount_price,list_price,price_detail,price_serve_tracking_id'
# fetch the data
res=requests.get(link).json()
print(res)
>>> {'courses': {'1596446': {'_class': 'pricing_result', 'price_serve_tracking_id': 'rbNYz3yCSiS2G1J62gtSzg', 'price': {'amount': 16.99, 'currency': 'EUR', 'price_string': '€16.99', 'currency_symbol': '€'}, 'list_price': {'amount': 119.99, 'currency': 'EUR', 'price_string': '€119.99', 'currency_symbol': '€'}, 'discount_price': {'amount': 17.0, 'currency': 'EUR', 'price_string': '€17', 'currency_symbol': '€'}, 'price_detail': {'amount': 119.99, 'currency': 'EUR', 'price_string': '€119.99', 'currency_symbol': '€'}}}, 'bundles': {}}

推荐阅读