首页 > 解决方案 > raise JSONDecodeError(“期望值”, s, err.value)

问题描述

我正在尝试抓取数据,但是代码会引发错误json.loads。当我追溯错误时,我意识到循环中的元素是None,所以json.loads无法运行。

有什么解决办法吗?

下面是我的代码:

import json
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
from datetime import datetime

start_time = datetime.now()


data = []
 
op = webdriver.ChromeOptions()
op.add_argument('--ignore-certificate-errors')
op.add_argument('--incognito')
op.add_argument('--headless')
driver = webdriver.Chrome(executable_path='D:/Desktop/Query/chromedriver.exe',options=op)
driver.get('https://www.cdiscount.com/f-1175520-MIS2008813786478.html')
link = 'https://www.cdiscount.com/f-1175520-MIS2008813786478.html'
soup = BeautifulSoup(driver.page_source, 'html.parser')
b = soup.prettify()
product_title = soup.find('title').getText()
reviews = soup.find_all("script",type="application/ld+json")
for element in reviews : 
     json_string = element.getText()
     json_dict = json.loads(json_string)
     data.append(json_dict)

标签: pythonjsonseleniumbeautifulsoup

解决方案


您可以尝试通过访问contents您的元素来读取 JSON。

for element in reviews: 
     json_string = ' '.join(element.contents)
     json_dict = json.loads(json_string)
     data.append(json_dict)

BeautifulSoup文档关于getText

如果您只想要文档或标签中的人类可读文本,您可以使用 get_text() 方法。

...

从 Beautiful Soup 版本 4.9.0 开始,当使用 lxml 或 html.parser 时, 、 和 标签的内容不被视为“文本”,因为这些标签不是页面的人类可见内容的一部分*

这就是为什么getText在您的情况下返回一个空字符串并且contents需要使用它的原因。


推荐阅读