如何在Python中解析html源代码中的javascript代码?

2024-09-30 01:27:53 发布

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

我试图在HTML源代码中的JavaScript标记中进行web抓取。在

情况:我可以找到适当的<script></script>标记。但是在这个标签里面,有一个大字符串,它需要被转换,然后被解析,这样我就可以得到我需要的精确数据。在

问题是:我不知道如何做到这一点,也找不到一个明确而令人满意的答案。在

代码如下:

我的目标是获得这些数据:"xe7fd4c285496ab91",这是内容的标识号,也称为"contentId"。在

import requests
import bs4
import re

url = 'https://www.khanacademy.org/computing/computer-programming/programming/drawing-basics/pt/making-drawings-with-code'
response = requests.get(url)
soup = bs4.BeautifulSoup(response.text,'html.parser') # by the way I am not sure if this is the right way to parse the link

item = soup.find(string=re.compile('contentId')) # with this line I can get directly to the exact javascript tag that I need

print(item) # but as you can see, it's a pretty big string, and I need to parse it to get the desired data. But you can find that the desired data "xe7fd4c285496ab91" is in it.

我试图使用json.parse(),但它不起作用:

^{pr2}$

获取此错误:

AttributeError: 'NavigableString' object has no attribute 'json'

我的问题是: 如何获得所需的数据? 有没有一个函数可以将字符串转换成javascript以便我可以解析它?或者一种将这个字符串转换成JSON文件的方法?在

(请记住,我将使用类似的HTML/JavaScript在多个链接上执行此操作)。在


Tags: theto数据字符串标记importgetparse

热门问题