Python 用转义字符解析 HTML

Python parse HTML with escape characters

我正在尝试从网站抓取数据,但数据 table 是由 JavaScript 呈现的。我没有使用像 Selenium 这样的工具来生成页面和 运行 脚本,而是找到了存储数据的脚本标签,并试图直接从那里提取数据。

代码如下:

import requests
from bs4 import BeautifulSoup
import json

url = 'https://www.etf.com/SPY'

result = requests.get(url)

c = result.content
html = BeautifulSoup(c, 'html.parser')

script = html.find_all('script')[-22]   #this is the script tag that has the data

script = script.contents

js = script[0]
data = js[31:-2]  #data is the json/dict which has the data

这是数据内容的片段:

s = json.loads(data)

s = s['etf_report_from_api']['modalInfoToActive']['top10Holdings']['data']

s = s[13:-2]

这里是 s 的片段:

此时内容看起来更像 HTML,但似乎转义字符未正确转义

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()

这是解析器的输出。它似乎能够识别某些标签,但由于格式问题而将其他标签识别为数据。

这个数据本质上是一个HTMLtable,但是我怎样才能正确decode/parse它来提取数据内容呢?

在我看来,您只需要取消转义字符串 s 中的 "/ 值,然后您就可以使用 bs4 成功解析标记:

soup = BeautifulSoup(s.replace(r"\"", '"').replace(r"\/", "/"), "html.parser")

for row in soup.find_all("tr"):
    name, value = row.find_all("td")
    print(f"{name.text}\t{value.text}")

结果:

Microsoft Corporation   3.55%
Apple Inc.  3.31%
Amazon.com, Inc.    3.11%
Facebook, Inc. Class A  1.76%
Berkshire Hathaway Inc. Class B 1.76%
...