python - 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)
解决方案
您可以尝试通过访问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
需要使用它的原因。
推荐阅读
- scala - 在 Spark 数据框中运行 UDF 时,不支持获取 org.apache.spark.sql.Column 类型的架构
- command-line - 我需要在一行中获取文件夹列表
- node.js - Angular 未在全新的 ubuntu 安装上运行
- flutter - Flutter dart_ping 包不工作。那么如何ping一些远程IP,如172.18.43.140?
- python - 针对不同类别使用不同颜色的散点图
- php - 页面在 laravel 中没有正确定向
- javascript - 天蓝色功能不在本地运行
- azure-active-directory - 为什么“signInAudience”:“AzureADMultipleOrgs”会导致“URI 方案无效或不受支持”
- google-chrome - AWS LB 粘性会话和 SameSite
- node.js - Angular CLI Docker 开发环境