【问题标题】:Beautiful Soup Web Scraper IndexError: list index out of rangeBeautiful Soup Web Scraper IndexError: list index out of range
【发布时间】:2021-12-27 10:13:40
【问题描述】:

我正在制作一个网络爬虫,它可以抓取雅虎财经并告诉我当前的股价是多少。

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

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 的初学者,所以任何帮助将不胜感激:)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    会发生什么?

    注意 总是先看看你的汤——这就是事实。内容总是与开发工具中的视图略有不同。

    没有<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
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 2018-02-08
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多