The problem
I have the following Page01.htm
<!DOCTYPE html><html lang="it-IT"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <head><title>Title here</title></head>
<body>
<script id="TargetID" type="application/json"><![CDATA[
{ "name":"Kate", "age":22, "city":"Boston"}
]]>
</script><script id=“AnotherID” type="application/json"><![CDATA[{ "name":"John", "age":31, "city":"New York"}]]>
</script>
</body></html>
and I want to extract the informations inside the JSON between the the script tags with ID=TargetID
.
What I've done
I wrote the following Python 3.6 code:
from bs4 import BeautifulSoup
import codecs
page_path="/Users/me/Page01.htm"
page = codecs.open(page_path, "r", "utf-8")
soup = BeautifulSoup(page.read(), "lxml")
vegas = soup.find_all(id="TargetID")
invalid_tags = ['script']
soup = BeautifulSoup(str(vegas),"lxml")
for tag in invalid_tags:
for match in soup.findAll(tag):
match.replaceWithChildren()
JsonZ = str(soup)
Now, if I look inside vegas
variable I can see
[<script id="TargetID" type="application/json"><![CDATA[ {
> "name":"Kate", "age":22, "city":"Boston"} ]]> </script>]
but if I try to remove the script tags (using this answer script), I get the following JsonZ
variable
'<html><body><p>[<![CDATA[\n{ "name":"Kate", "age":22, "city":"Boston"}\n]]>\n]</p></body></html>'
that have no script tags but have another 3 tags (<html><body><p>
) completely unuseful.
My target is to get the following string { "name":"Kate", "age":22, "city":"Boston"}
to load with Python JSON modules.
", "").replace("
", "")` – skinnedpanda Nov 17 '22 at 20:07