【问题标题】:Python parse HTML with escape charactersPython 使用转义字符解析 HTML
【发布时间】:2019-02-02 19:43:59
【问题描述】:

我正在尝试从网站上抓取数据,但数据表是由 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

这是数据内容的 sn-p:

s = json.loads(data)

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

s = s[13:-2]

这是 s 的外观的 sn-p:

此时内容看起来更像 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()

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

此数据本质上是一个 HTML 表格,但我如何正确解码/解析它以提取数据内容?

【问题讨论】:

    标签: python html beautifulsoup escaping html-parsing


    【解决方案1】:

    在我看来,您只需在字符串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}")
    

    结果:

    微软公司 3.55% 苹果公司 3.31% 亚马逊公司 3.11% Facebook, Inc. A 类 1.76% 伯克希尔哈撒韦公司 B 类 1.76% ...

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2020-07-30
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多