我想使用python访问HTML页面中的变量

2024-03-28 23:13:53 发布

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

我试图创建一个函数,用于检索项目页面上auchan站点上的数据变量中的productStockLevel: "inStock"。 我被卡住了,因为我无法访问数据变量,我在互联网上搜索,但找不到任何东西,或者可能是我用错了。 目前,我只能从数据变量所在的位置获取脚本[4]。 如果有人能帮助我,我将非常感激我一直在工作的1h30

代码:

import requests
from bs4 import BeautifulSoup

session = requests.session()

def get_stock():
    global session
    productPage = 'https://www.auchan.fr/power-a-etui-de-protection-silhouette-pikachu-nintendo-switch/p-c1334312'
    response = session.get(productPage)
    soup = BeautifulSoup(response.content, "html.parser")
    scripts = soup.find_all('script')[4]
    print(scripts)

get_stock()

1条回答
网友
1楼 · 发布于 2024-03-28 23:13:53

尝试:

import re
import json
import requests

url = "https://www.auchan.fr/power-a-etui-de-protection-silhouette-pikachu-nintendo-switch/p-c1334312"

html_doc = requests.get(url).text
data = re.search(r"var product = (.*);", html_doc).group(1)
data = json.loads(data)

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

print("Stock level status:", data["stock"]["stockLevelStatus"]["code"])

印刷品:

Stock level status: inStock

data变量还包含其他信息:

{
    "code": "C1334312",
    "name": "\u00c9tui de Protection Silhouette Pikachu Nintendo Switch",
    "url": "/power-a-etui-de-protection-silhouette-pikachu-nintendo-switch/p-c1334312",
    "description": "C\u00e9l\u00e9brez votre amour de Pok\u00e9mon avec cet \u00e9tui de protection sous licence officielle qui stocke la console Nintendo Switch en mode portable. L'\u00e9tui pr\u00e9sente la silhouette de Pikachu, une doublure en feutre et un rabat de protection d'\u00e9cran rembourr\u00e9 avec rangement pour le jeu.",
    "purchasable": true,
    "stock": {
        "stockLevelStatus": {
            "code": "inStock",
            "type": "StockLevelStatus"
        },
        "stockLevel": 86,
        "stockThreshold": null,
        "supplyDelay": 3
    },
    "futureStocks": null,
    "availableForPickup": null,
    "averageRating": null,
    "numberOfReviews": null,
    "summary": "",
    "manufacturer": null,
    "variantType": null,
    "price": {
        "currencyIso": "EUR",
        "value": 10.0,

...and so on.

相关问题 更多 >