【发布时间】: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