python - 清理抓取结果以返回锚文本,而不是 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)
但收效甚微。指针表示赞赏!
解决方案
不确定,但我认为您可能正在寻找以下内容:
代替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
等等
推荐阅读
- jwt - Zoom API:帐户未启用 REST API
- maps - HERE 有 Parcel 边界数据吗?
- java - 如何在 Spring 中将 Redis Http 会话超时设置为无限制
- javascript - 将 python 脚本与 html 的 java 脚本混合
- visual-studio-code - Bash终端不允许打字
- java - JSON字符串到JAXB java对象解组
- docker - docker-compose mariadb docker-entrypoint-initdb.d sql 未执行
- maven - “mvn”命令未被识别为内部或外部命令,正在工作
- nuxt.js - 调用异步方法时不是函数错误吗?
- node.js - 获取 req.user.following 未定义