【问题标题】:trying to test a code that scrape from yahoo finance试图测试从 yahoo Finance 抓取的代码
【发布时间】:2021-02-04 01:30:57
【问题描述】:

我是 python 初学者,但我喜欢通过测试和尝试来学习这门语言。

所以有一个雅虎网络爬虫代码来抓取特定股票的最后价格,但它对我不起作用我不知道问题。

..

代码:

# -*- coding: utf-8 -*-
import bs4
import requests
from bs4 import BeautifulSoup


def parsePrice():
    r = requests.get('https://finance.yahoo.com/quote/fb?p=FB')
    soup = bs4.BeautifulSoup(r.text,"xml")
    price = soup.find('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
    return price

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

错误:

price = soup.find('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
AttributeError: 'NoneType' object has no attribute 'find'

也许这很容易,但请记住我是初学者。

提前致谢

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    使用lxml 代替xml 作为解析器。

    打印时无需将parsePrice转换为字符串,因为它的输出已经是字符串了。

    import requests
    from bs4 import BeautifulSoup
    
    def parsePrice():
        r = requests.get('https://finance.yahoo.com/quote/fb?p=FB')
        soup = BeautifulSoup(r.text,"lxml")
        price = soup.find('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
        return price
    
    print('the current price: ' + parsePrice())
    

    输出:

    the current price: 216.08
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2016-05-28
      • 2020-03-12
      • 2013-10-02
      • 1970-01-01
      相关资源
      最近更新 更多