首页 > 解决方案 > 清理抓取结果以返回锚文本,而不是 HTML

问题描述

我正在尝试从给定的 URL 中获取曲棍球棒的价格。最终我还想获取名称+ 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)

但收效甚微。指针表示赞赏!

标签: pythonweb-scrapingbeautifulsoup

解决方案


不确定,但我认为您可能正在寻找以下内容:

代替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

等等


推荐阅读