【问题标题】:Converting a string from scraped javascript into a python dictionary将字符串从抓取的 javascript 转换为 python 字典
【发布时间】:2021-06-21 06:25:03
【问题描述】:

我想在下面的链接中爬取产品的产品描述。

我尝试使用 selenium 进行抓取,但信息受网站保护,因此我通过 selenium 获得的所有信息与 requests。所以为了让脚本运行得更快,我使用 requests 来抓取它。

下面是代码:

import requests
from bs4 import BeautifulSoup as BS

res= requests.get("https://www.real.de/product/345246038/")
soup=BS(res.text,'lxml')
code=soup.prettify()
split =  code.split("attributes:")
for value in split:
    after=value.split(",condition$:b")
    for value in after:
        if "{default:[{name:" in value:
            clean = value.replace(",highlighted:void 0}}","}").replace(": None","")
       

这是变量 clean 中的字符串:

我将 clean 转换成字典:

import yaml
d = yaml.load(clean)

但它的格式不像字典那样正确:因为并非所有单词都在双引号(“”)中

所以我使用正则表达式仅提取字符串中不在双引号中的单词。这是代码:

r = re.compile(r'[{,:][a-zA-z]+[:}]', flags=re.I | re.X)
string = r.findall(clean)  
ta=[]          
for w in string :
    m = re.search('[a-zA-z]+', w)
    if m:
        new = str('"')+m.group(0)+str('"')
        ta.append(new)
                        

但是。我不知道如何将双引号 ("") 中的单词再次放入 clean 变量中。

你能帮帮我吗?

【问题讨论】:

  • 您是否尝试将文本解析为 JSON?
  • 我试过了:import json data = json.loads(clean)。但它会抛出错误: JSONDecodeError: Expecting property name 用双引号括起来
  • 是的,json 不会像那样解析字符串形式的 JavaScript 对象。

标签: python regex string beautifulsoup python-requests


【解决方案1】:

你可以试试(?!"),意思是匹配不带引号的字符

if "{default:[{name:" in value:
    clean = value.replace(",highlighted:void 0}}","}").replace(": None","")
    # add the lines below
    clean = re.sub(r'(\{|,)(?!")(\w+?):', r'\1"\2":', clean)
    clean = re.sub(r':(?!")(\w+?)(\}|,)', r':"\1"\2', clean)
    jsonData = json.loads(clean)
    print(json.dumps(jsonData, indent=2))

【讨论】:

  • 不客气,请将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 2018-05-19
  • 2013-03-13
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2013-02-19
相关资源
最近更新 更多