从Python BeautifulSoup中的javascript源中提取值



我对网络抓取很陌生,想知道是否可以从javascript应用程序中提取我需要的信息。目前,我在python中使用beautifulsoup,并对html解析器的输出感兴趣:

<p><script>
var acct = '488'; var loc = ''; var cat = ''; var stylesheet=''; var hideLastnames = true;
var jsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write("<scr"+"ipt src='"+jsHost+"ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js' type='text/javascript'></scr"+"ipt>");
document.write("<scr"+"ipt>var jQuery = jQuery.noConflict(true);</scr"+"ipt>");
document.write("<scr"+"ipt src='"+jsHost+"www.groupexpro.com/schedule/embed/schedule_embed_responsive.js.php?a="+acct+"' type='text/javascript'></scr"+"ipt>");
</script></p>

在实际网站中(https://recreation.gocrimson.com/fitness/schedules),看起来像这样。理想情况下,我希望存储一个json,其中包含表中列出的所有信息。有人做过类似的事情吗?

https://recreation.gocrimson.com/fitness/schedules请求不同的URL以获取JSONP格式的日程数据。

URL:https://www.groupexpro.com/schedule/embed/json.php?schedule&instructor_id=true&format=jsonp&a=488&location=&category=&start=1587380400&end=1587898800

尝试理解URL,并根据您的目的对其进行修改。

示例

from bs4 import BeautifulSoup
import requests
import json

headers ={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0"}
page=requests.get("https://www.groupexpro.com/schedule/embed/json.php?schedule&instructor_id=true&format=jsonp&a=488",headers=headers)
#Extract json from jsonp
jsondata='{'+page.text.split('{')[1].split('}')[0]+'}'
#can also be loaded into python dict using
data=json.loads(jsondata)

最新更新