尝试测试从雅虎财经抓取的代码

问题描述 投票:0回答:2

我是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
2个回答
0
投票

使用

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

0
投票

我尝试了 MendelG 解决方案,仍然有同样的错误,也许这是由于 2020 年以来的一些变化造成的:

compat_exec 中的文件 ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\spyder_kernels\py3compat.py:356 exec(代码,全局变量,局部变量)

文件 c:\users\user\documents\python_program\untitled28.py:17 print('当前价格:' + parsePrice())

parsePrice 中的文件 c:\users\user\documents\python_program\untitled28.py:14 价格 = soup.find('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text

AttributeError:“NoneType”对象没有属性“find”

© www.soinside.com 2019 - 2024. All rights reserved.