【问题标题】:How to find the productId present in website(CDATA) using Beautiful Soup如何使用 Beautiful Soup 查找网站(CDATA)中存在的 productId
【发布时间】:2021-08-08 09:53:21
【问题描述】:

我想使用漂亮的汤从给定的脚本或网站上的任何 id 中提取 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))

【问题讨论】:

    标签: web-scraping beautifulsoup cdata


    【解决方案1】:

    您需要使用.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
    

    【讨论】:

    • 它的作品可以请解释这里使用的正则表达式如何(re.search(r"single_product = ({.*})", s.string).group(1))
    • 正则表达式获取{} 之间的所有内容,包括括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    相关资源
    最近更新 更多