拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 BeautifulSoupWebScraperIndexError:串列索引超出范围

BeautifulSoupWebScraperIndexError:串列索引超出范围

白鹭 - 2022-03-08 1987 0 0

我正在制作一个 Web 抓取工具,可以抓取 Yahoo Finance 并告诉我当前的股价是多少。

运行程序后我不断收到这样的错误

IndexError: list index out of range

这是代码

def parsePrice():
r=requests.get('https://finance.yahoo.com/quote/F?p=F')
soup=bs4.BeautifulSoup(r.text,'xml')
#the next line is the supposed problem
price=soup.find_all('div',{'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].Find('span').text
return price




while True:
    print('the current price is: ' str(parsePrice())) 

我是 python 的初学者,所以任何帮助将不胜感激:)

uj5u.com热心网友回复:

怎么了?

注意 总是先看看你的汤 - 这就是真相。内容可能总是与开发工具中的视图略有不同。

没有<div>您在汤中搜索的此类课程,这就是结果集为空且无法匹配采摘索引的原因[0]

怎么修?

  1. headers在您的请求中添加一些,以显示您可能是“浏览器”:

    headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
    
  2. 选择更具体的元素 - 因为您知道请求中的资料符号,您可以直接选择它:

    soup.select_one('[data-symbol="F"]')['value']
    

例子

注意 抓取的第一条规则:不要伤害网站!意味着您查询的数量和频率不应给网站、服务器带来负担。因此,请import time -> time.sleep(60)在您的请求之间添加一些延迟 ( ) 或使用官方 api

import bs4
import requests
headers ={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}


def parsePrice():
    r=requests.get('https://finance.yahoo.com/quote/F?p=F', headers=headers)
    soup=bs4.BeautifulSoup(r.text,'xml')
    price = soup.select_one('[data-symbol="F"]')['value']
    return price

while True:
    print('the current price is: ' str(parsePrice()))

输出

the current price is: 20.25
the current price is: 20.25
the current price is: 20.25
the current price is: 20.25
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *