使用beautifulsoup从<script>提取数据

2024-09-30 05:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python和Beautifulsoup来获取一些数据。我知道如何从脚本标签中获取文本。[]之间的数据是有效的json。在

<script>
    dataLayer = 
[  
  {  
  "p":{  
         "t":"text1",
         "lng":"text2",
         "vurl":"text3"
       },
  "c":{  },
  "u":{  },
  "d":{  },
  "a":{  }
  }
]
</script>

我读过这个回复,它几乎达到了我想要的效果: Extract content of <Script with BeautifulSoup

这是我的代码:

^{pr2}$

我理想的做法是:

json_dict = json.loads(raw_data)

并通过字典访问数据。但这不起作用是因为

"<script> dataLayer =" 

在有效的json和末尾的script标记之前。我尝试过将原始数据裁剪为字符串,如下所示:

raw_data[20:]

但这没用,因为soup对象不是字符串。在

如何使raw_data变量仅包含块引号[]之间的文本?在

编辑:这似乎有效。它避免了正则表达式,并解决了尾随字符的问题。谢谢你的建议。在

url = "www.example.com"
html = urllib.request.urlopen(url)
soup = BeautifulSoup(html, "html.parser")

# get the script tag data and convert soup into a string
data = str(soup.find("script"))

# cut the <script> tag and some other things from the beginning and end to get valid JSON
cut = data[27:-13]

# load the data as a json dictionary
jsoned = json.loads(cut)

Tags: andthe数据字符串文本jsondataraw
2条回答
>>> import re
>>> soup.find_all(re.compile("\[(.*?)\]"))

你可以用regex

您必须创建一个只接受[]之间文本的regex规范

here a link of common regex usage within beautifulsoup

here the regex to extract from between square brackets

使用.text获取<script>标记内的内容,然后替换dataLayer =

raw_data = soup.find("script")
raw_data = raw_data.text.replace('dataLayer =', '')
json_dict = json.loads(raw_data)

相关问题 更多 >

    热门问题