【问题标题】:raise JSONDecodeError(“Expecting value”, s, err.value)raise JSONDecodeError(“期望值”, s, err.value)
【发布时间】:2021-03-05 00:18:58
【问题描述】:

我正在尝试爬取数据,但是代码会引发 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)

【问题讨论】:

    标签: python json selenium beautifulsoup


    【解决方案1】:

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

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

    The BeautifulSoup documentation about getText:

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

    ...

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

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

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 2021-02-23
      • 2022-06-11
      • 2019-09-18
      • 2021-09-29
      • 2019-08-06
      • 2020-04-19
      • 2020-09-04
      • 1970-01-01
      相关资源
      最近更新 更多