【问题标题】:Why Read_HTML from Python Pandas not working?为什么 Python Pandas 中的 Read_HTML 不起作用?
【发布时间】:2021-09-15 20:46:41
【问题描述】:

我想使用 Python Pandas Read_HTML() 函数从 Yahoo Finance 表中抓取信息,如屏幕截图所示,红色边框。

但是,我收到了 HTTPError: HTTP Error 404: Not Found

这是我的代码输出:

!pip install pandas
!pip install requests
!pip install bs4
!pip install requests_html
!pip install pytest-astropy
!pip install nest_asyncio
!pip install plotly

import pandas as pd
from bs4 import BeautifulSoup
import requests
import requests_html
import nest_asyncio
import lxml
import html5lib
nest_asyncio.apply()

url_link = "https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27"
read_html_pandas_data = pd.read_html(url_link)

【问题讨论】:

    标签: python html pandas web-scraping


    【解决方案1】:

    尝试如下:

    import pandas as pd
    import requests
    url_link = 'https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27'
    r = requests.get(url_link,headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'})
    read_html_pandas_data = pd.read_html(r.text)
    print(read_html_pandas_data)
    

    【讨论】:

    • 您好,感谢您的回复!但是,我收到了这样的输出:[ 0 0 马上回来...谢谢您的耐心...]
    • 只需添加用户代理
    • 现在你会得到数据
    • 如果你想访问网站的数据,那么你需要得到你的真实身份,这就是为什么你必须注入用户代理作为标题。谢谢
    • 其实我来自scrapy developer。现在您可以根据需要使用 pandas 进行一些数据分析,您可以从这里获得帮助:youtube.com/…
    【解决方案2】:

    因为需要一个不能用read_html 指定的用户代理标头。您可以先使用requests 抢表,指定适当的标题,然后移交给 pandas:

    from pandas import read_html as rh
    import requests
    from bs4 import BeautifulSoup as bs
    
    r = requests.get('https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27', headers = {'User-Agent':'Mozilla/5.0'})
    soup = bs(r.content, 'lxml')
    table = rh(str(soup.select_one('[data-test="historical-prices"]')))[0]
    print(table)
    

    【讨论】:

    • 您好,感谢您的回复!有没有办法将行转换为列并将它们放在 DataFrame 中?这是当前的输出: 日期 \ 0 2021 年 7 月 2 日 1 2021 年 7 月 1 日 2 2021 年 6 月 30 日
    • 表已经是一个数据框。它有一个 transpose() 方法。 pandas.pydata.org/pandas-docs/stable/reference/api/…
    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2019-12-02
    • 2022-11-25
    • 2020-09-01
    • 2021-07-28
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多