如何使用 Beautiful Soup 查找网站(CDATA)中存在的产品 ID

How to find the productId present in website(CDATA) using Beautiful Soup

我想使用 beautiful soup 从给定的脚本或网站上出现的任何位置提取 productId 值 (186852001461)。

<script type="text/javascript">
 /* <![CDATA[ */
var bv_single_product = {"prodname":"Honey Graham Gelato","productId":"186852001461"};
/* ]]> */
</script>

我的代码

import re
import requests
from bs4 import BeautifulSoup
final = "https://www.talentigelato.com/products/honey-graham-gelato"
response = requests.get(final, timeout=35)
soup = BeautifulSoup(response.content, "html.parser") 
s = soup.findAll('script',attrs={'type': 'text/javascript'} )[17]
print(type(s))
html_content = str(s)
html_content = s.prettify()
print(html_content))

您需要使用 .string,然后使用 regex,这样您就可以将值转储到 json.loads()

方法如下:

import json
import re

import requests
from bs4 import BeautifulSoup

final = "https://www.talentigelato.com/products/honey-graham-gelato"
response = requests.get(final, timeout=35)
soup = BeautifulSoup(response.content, "html.parser")
s = soup.findAll('script', attrs={'type': 'text/javascript'})[17]
data = json.loads(re.search(r"single_product = ({.*})", s.string).group(1))
print(data["productId"])

输出:

186852001461