首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >雅虎财经python上的某些股票和页面出现404错误

雅虎财经python上的某些股票和页面出现404错误
EN

Stack Overflow用户
提问于 2021-07-06 00:10:24
回答 2查看 1.9K关注 0票数 1

我正在尝试从雅虎财经这个网址https://finance.yahoo.com/quote/AAPL/key-statistics?p=AAPL抓取数据。在运行下面的python代码之后,我得到了以下HTML响应

代码语言:javascript
复制
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests, lxml
from lxml import html

stockStatDict = {}
stockSymbol = 'AAPL'
URL = 'https://finance.yahoo.com/quote/'+ stockSymbol + '/key-statistics?p=' + stockSymbol
page = requests.get(URL)
print(page.text)


<!DOCTYPE html>
  <html lang="en-us"><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <meta charset="utf-8">
      <title>Yahoo</title>
      <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <style>
  html {
      height: 100%;
  }
  body {
      background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;
      background-size: cover;
      height: 100%;
      text-align: center;
      font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif;
  }
  table {
      height: 100%;
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;
      border-spacing: 0;
      border: none;
  }
  h1 {
      font-size: 42px;
      font-weight: 400;
      color: #400090;
  }
  p {
      color: #1A1A1A;
  }
  #message-1 {
      font-weight: bold;
      margin: 0;
  }
  #message-2 {
      display: inline-block;
      *display: inline;
      zoom: 1;
      max-width: 17em;
      _width: 17em;
  }
      </style>
  <script>
    document.write('<img src="//geo.yahoo.com/b?s=1197757129&t='+new Date().getTime()+'&src=aws&err_url='+encodeURIComponent(document.URL)+'&err=%<pssc>&test='+encodeURIComponent('%<{Bucket}cqh[:200]>')+'" width="0px" height="0px"/>');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+new Date().getTime()+"&src=aws&err_url="+encodeURIComponent(document.URL)+"&err=%<pssc>&test="+encodeURIComponent('%<{Bucket}cqh[:200]>');
  </script>
  </head>
  <body>
  <!-- status code : 404 -->
  <!-- Not Found on Server -->
  <table>
  <tbody><tr>
      <td>
      <img src="https://s.yimg.com/rz/p/yahoo_frontpage_en-US_s_f_p_205x58_frontpage.png" alt="Yahoo Logo">
      <h1 style="margin-top:20px;">Will be right back...</h1>
      <p id="message-1">Thank you for your patience.</p>
      <p id="message-2">Our engineers are working quickly to resolve the issue.</p>
      </td>
  </tr>
  </tbody></table>
  </body></html>

我很困惑,因为我使用以下代码在这个URL https://finance.yahoo.com/quote/AAPL?p=AAPL的摘要选项卡上抓取数据没有任何问题

代码语言:javascript
复制
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests, lxml
from lxml import html
stockDict = {}

stockSymbol = 'AAPL'
URL = 'https://finance.yahoo.com/quote/'+ stockSymbol + '?p=' + stockSymbol
page = requests.get(URL)
print(page.text)

soup = BeautifulSoup(page.content, 'html.parser')


stock_data = soup.find_all('table')

stock_data
for table in stock_data:
    
    trs = table.find_all('tr')
    
    for tr in trs:
        
        
        tds = tr.find_all('td')
        
        if len(tds) > 0:
         
            stockDict[tds[0].get_text()] = [tds[1].get_text()]


stock_sum_df = pd.DataFrame(data=stockDict)
print(stock_sum_df.head())
print(stock_sum_df.info())

有人知道我做错了什么吗?我也在使用雅虎财经的免费版本,如果这有什么不同的话。

EN

回答 2

Stack Overflow用户

发布于 2021-07-06 00:35:04

所以我知道你的问题了。

用户代理请求报头包含一个特征字符串,该字符串允许网络协议对等方识别请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。在服务器端验证User-Agent头是一项常见的操作,因此请确保使用有效的浏览器User-Agent字符串,以避免被阻塞。

来源http://go-colly.org/articles/scraping_related_http_headers/)

您唯一需要做的就是设置一个合法的用户代理。因此,添加标头来模拟浏览器:

代码语言:javascript
复制
# This is a standard user-agent of Chrome browser running on Windows 10 
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } 

示例:

代码语言:javascript
复制
import requests 
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
stockSymbol = 'AAPL'
url = 'https://finance.yahoo.com/quote/'+ stockSymbol + '/key-statistics?p=' + stockSymbol
resp = requests.get(url, headers=headers, timeout=5).text 
print(resp)

此外,您还可以添加另一组标头来伪装成合法的浏览器。添加更多标题,如下所示:

代码语言:javascript
复制
headers = { 
    'User-Agent'      : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 
    'Accept'          : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
    'Accept-Language' : 'en-US,en;q=0.5',
    'DNT'             : '1', # Do Not Track Request Header 
    'Connection'      : 'close'
}

这些事情通常由于两个主要原因而起作用:

  1. Anti-automation系统(检测bots/crawlers)
  2. Sites的系统,倾向于根据您使用的浏览器调整内容。

因此,在设计自动化系统时,在头文件中提供用户代理始终是一个好主意。

票数 7
EN

Stack Overflow用户

发布于 2021-07-06 00:16:34

不确定是什么导致了这个问题,以及你的项目的意图是什么。然而,如果你的意图是能够对雅虎金融数据做一些事情-而不是学习如何抓取数据,那么下面的模块可以帮助你(https://pypi.org/project/yahoo-finance/)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68259148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档