如何从一个网站的多个链接中获取数据并将其制成表格

2024-04-20 13:59:29 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码正在执行并提供指向单个网站数据的多个链接。代码提到了网站。该网站有多个链接的数据,然后作为一个单一的表格

你能建议一下在这段代码中做了哪些更改,以便在不导入任何其他库和表格的情况下获取数据吗?你知道吗

    #import libraries
    import re 
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import urllib.request as ur
    from bs4 import BeautifulSoup

    s = ur.urlopen("https://financials.morningstar.com/ratios/r.html?t=AAPL")
    s1 = s.read()
    print(s1)

    soup = BeautifulSoup(ur.urlopen('https://financials.morningstar.com/ratios/r.html?t=AAPL'),"html.parser")
title = soup.title
print(title)

text = soup.get_text()
print(text)
links = []
for link in soup.find_all(attrs={'href': re.compile("http")}):
    links.append(link.get('href'))

print(links)

预期结果应为所列比率的表格形式,每个比率可作为字典列出,键为年份,值为比率


Tags: 数据代码textimporttitle网站链接html
1条回答
网友
1楼 · 发布于 2024-04-20 13:59:29

1)硒和熊猫有一种方法。您可以查看最终结构here。内容是JavaScript加载的,所以我认为您可能需要额外的库。你知道吗

2)有人致电:

https://financials.morningstar.com/finan/financials/getKeyStatPart.html?&callback=jsonp1555262165867&t=XNAS:AAPL&region=usa&culture=en-US&cur=&order=asc&_=1555262166853

返回包含页面信息的json。你可以试着用requests。你知道吗

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import copy

d = webdriver.Chrome()
d.get('https://financials.morningstar.com/ratios/r.html?t=AAPL')
tables = WebDriverWait(d,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#tab-profitability table")))
results = []

for table in tables:
    t = pd.read_html(table.get_attribute('outerHTML'))[0].dropna()
    years = t.columns[1:]
    for row in t.itertuples(index=True, name='Pandas'):
        record = {row[1] : dict(zip(years, row[2:]))}
        results.append(copy.deepcopy(record))
print(results)

d.quit()

最后,您将列出所有17行。前两行显示在这里,第2行展开以显示年份与值的配对。你知道吗

相关问题 更多 >