试图通过使用漂亮的soap从html代码中获取值,但很难获取

2024-10-04 09:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在漂亮的soap代码的帮助下,试图从网站https://www.coop.se/butiker-erbjudanden/coop/coop-ladugardsangen-/找到下图enter image description here中显示的值。但我得到的唯一值是价格数字,而不是“st”值

这是我尝试使用的代码来获取它

代码

test = product.find('span', class_='Splash-content ')
    print(Price.text)

Tags: 代码httpstest网站www价格数字product
2条回答
import requests
from bs4 import BeautifulSoup as bsoup
site_source = requests.get("https://www.coop.se/butiker-erbjudanden/coop/coop-ladugardsangen-/").content
soup = bsoup(site_source, "html.parser")
all_items = soup.find("div", class_="Section Section margin")
item_list = soup.find_all("span", class_="Splash-content")
for item in item_list:
    print("Price: ",item.find("span", class_="Splash-priceLarge").text)
    if item.find("span", class_="Splash-priceSub Splash-priceUnitNoDecimal"):
        print("Unit: ",item.find("span", class_="Splash-priceSub Splash-priceUnitNoDecimal").text)

在某些情况下,该装置丢失,因此我们希望确保能够处理该问题

我的理解是,你基本上想打印每个项目的价格和单位,所以这就是我试图做的

尝试:

url = "https://www.coop.se/butiker-erbjudanden/coop/coop-ladugardsangen-/"
try:
    page = urllib.request.urlopen(url, timeout=20)
except HTTPError as e:
    page = e.read()
soup = BeautifulSoup(page, 'html.parser')
body = soup.find('body')
result = body.find("span", class_="Splash-content")
print(result.get_text())

对我来说,成功了

相关问题 更多 >