I have a webpage with the following data that I would like to scrape in the CData section of that webpage.
<script type="text/javascript">//<![CDATA[
car.app =
{"lat":26.175625,"lon":-80.13808,"zoom":"13","yellow":"\/img\/icons\/yellow.png","cars":[{"CAR_ID":"715383","ID":"538070521","UID":"0","CARNAME":"MAZDA","TYPE_COLOR":"0","LAT":"26.13437","LON":"-80.11906","COURSE":"100","SPEED":"0","LENGTH":"12","STATE":"OH"}]
...
...
//]]></script>
I would like to grab the car.app variable inside of the CData, but I am unsure how to parse that in python.
import bs4 as bs
import urllib.request
class AppURLopener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
opener = AppURLopener()
response = opener.open(url)
c = response.read()
soup = bs.BeautifulSoup(c, "html.parser")
print(soup)
I think the only way to solve your problem is to parse that specific tag using BeautifulSoup and then do some string manipulation to achieve your goal.
Code:
import bs4 as bs
import urllib.request
c = '''
<script type="text/javascript">//<![CDATA[
car.app =
{"lat":26.175625,"lon":-80.13808,"zoom":"13","yellow":"\/img\/icons\/yellow.png","cars":[{"CAR_ID":"715383","ID":"538070521","UID":"0","CARNAME":"MAZDA","TYPE_COLOR":"0","LAT":"26.13437","LON":"-80.11906","COURSE":"100","SPEED":"0","LENGTH":"12","STATE":"OH"}]
...
...
//]]></script>
'''
soup = bs.BeautifulSoup(c, "html.parser")
script = soup.find('script')
print(str(script.text).split('car.app =')[1].split('...')[0].replace('\n', ''))
Output:
{"lat":26.175625,"lon":-80.13808,"zoom":"13","yellow":"\/img\/icons\/yellow.png","cars":[{"CAR_ID":"715383","ID":"538070521","UID":"0","CARNAME":"MAZDA","TYPE_COLOR":"0","LAT":"26.13437","LON":"-80.11906","COURSE":"100","SPEED":"0","LENGTH":"12","STATE":"OH"}]