我正在尝试从给定的网址中删除曲棍球棒的价格。最终,我也想获取名称和URL,但是我认为解决这个问题不是必需的。
这就是我所拥有的:
import requests
from pandas.io.json import json_normalize
from bs4 import BeautifulSoup
url = 'https://www.prohockeylife.com/collections/senior-hockey-sticks'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
stick_names = soup.find_all(class_='product-title')
stick_prices = soup.find_all(class_='regular-product')
print(stick_prices)
上面的代码成功返回了曲棍球棒的价格,但是看起来像这样:
[<p class="regular-product">
<span>$319.99</span>
</p>, <p class="regular-product">
<span>$339.99</span>
</p>, <p class="regular-product">
<span>$319.99</span>
我想清理一下,只退回实际价格。
我尝试了一些事情,包括:
dirty_prices = soup.find_all(class_='regular-product')
clean_prices = dirty_prices.get('a')
print(clean_prices)
但是收效甚微。指针表示赞赏!
答案 0 :(得分:2)
不确定,但是我认为以下是您可能要寻找的东西:
使用而不是print(stick_prices)
,
for name,price in zip(stick_names,stick_prices):
print(name["href"],name.text,price.text)
输出的开始是:
/collections/senior-hockey-sticks/products/ccm-ribcor-trigger-3d-sr-hockey-stick
CCM RIBCOR TRIGGER 3D SR HOCKEY STICK
$319.99
/collections/senior-hockey-sticks/products/bauer-vapor-1x-lite-sr-hockey-stick
BAUER VAPOR 1X LITE SR HOCKEY STICK
$339.99
等
答案 1 :(得分:1)
您需要.text属性,您也可以在列表理解期间将其提取。然后列出/压缩最后的名称/价格元组列表
import requests
from bs4 import BeautifulSoup
url = 'https://www.prohockeylife.com/collections/senior-hockey-sticks'
headers = {'user-agent': 'Mozilla/5.0'}
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
stick_names = [item.text.strip() for item in soup.find_all(class_='product-title')]
stick_prices = [item.text.strip() for item in soup.find_all(class_='regular-product')]
print(list(zip(stick_names, stick_prices)))