【发布时间】:2020-06-03 20:30:00
【问题描述】:
我正在尝试学习 BeatifulSoup,但目前无法提取价格(尤其是在有折扣/删除的情况下)。我只在有折扣时才感兴趣(itemprop = "offers"),对于这个练习,我只想提取原始价格。
可以通过检查此页面获得完整的 HTML: https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests
在下面的 HTML 中突出显示所需的目标:
我试过了
from bs4 import BeautifulSoup
import requests
import pandas as pd
import json
page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')
div_price = []
for section_tag in soup.find_all('div', class_='product-tile__meta-primary'):
for div_prices in section_tag.find_all('div', class_='price'):
if div_prices.get('itemprop') == 'offers':
for x in div_prices.find_all('span', {'class':'strike-through list'}):
for y in x.find_all('span', class_='value'):
div_price.append(y.get('content'))
else:
continue
上面的代码给了我想要的价格——我只想要原价(499 美元),不是折扣价(349.30 美元)——但是它会重复多次:(
['499.00', '435.00', '879.00', '999.00', '799.00', '499.00', '435.00', '879.00', '999.00', '799.00', '499.00', '435.00', '879.00', '999.00', '799.00', '499.00', '435.00', '879.00', '999.00', . . .
此外,我对嵌套循环并不感到自豪,我希望社区可以帮助修复这两个错误(感觉就像我在这里遗漏了一些简单的东西,但我无法理解它):
- 如果有更好的方法不使用所有循环,我会全力以赴
- 除了继续使用 find_all(仍在 BeautifulSoup 中)之外,还有更好的方法来提取所需信息吗?
【问题讨论】:
标签: python loops parsing web-scraping beautifulsoup