1

我正在使用布尔“Hello!Python”中的以下代码:

import urllib2
from bs4 import BeautifulSoup
import os

def get_stock_html(ticker_name):
    opener = urllib2.build_opener(urllib2.HTTPRedirectHandler(),urllib2.HTTPHandler(debuglevel=0),)
    opener.addhaders = [('User-agent', "Mozilla/4.0 (compatible; MSIE 7.0; " "Windows NT 5.1; .NET CLR 2.0.50727; " ".NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")]
    url = "http://finance.yahoo.com/q?s=" + ticker_name
    response = opener.open(url)
    return ''.join(response.readlines())

def find_quote_section(html):
    soup = BeautifulSoup(html)
    # quote = soup.find('div', attrs={'class': 'yfi_rt_quote_summary_rt_top'})
    quote = soup.find('div', attrs={'class': 'yfi_quote_summary'})
    return quote

def parse_stock_html(html, ticker_name):
    quote = find_quote_section(html)
    result = {}
    tick = ticker_name.lower()

    result['stock_name'] = quote.find('h2').contents[0]

if __name__ == '__main__':
    os.system("clear")
    html = get_stock_html('GOOG')
    # print find_quote_section(html)
    print parse_stock_html(html, 'GOOG')

收到以下错误:

Traceback (most recent call last):
  File "dwlod.py", line 33, in <module>
    print parse_stock_html(html, 'GOOG')
  File "dwlod.py", line 25, in parse_stock_html
    result['stock_name'] = quote.find('h2').contents[0]
AttributeError: 'NoneType' object has no attribute 'contents'

我是一个新手,真的不知道该怎么做。书是错的吗?

添加

我刚刚替换result['stock_name'] = quote.find('h2').contents[0]为:

x = BeautifulSoup(html).find('h2').contents[0]
return x

现在,什么都没有返回,但错误不再出现。那么,原来的python语法有问题吗?

4

1 回答 1

2

虽然雅虎财经已经有一段时间没有真正改变他们的布局,但似乎他们可能在这本书出版后稍微调整了一下,你需要的信息,比如h2包含股票代码的信息,可以在yfi_rt_quote_summary其中找到容器位于某个东西的上放yfi_quote_summary

def find_quote_section(html):
    soup = BeautifulSoup(html)        
    quote = soup.find('div', attrs={'class': 'yfi_rt_quote_summary'})
    return quote

另请注意,result如果我们想打印某些东西,我们需要None返回:

def parse_stock_html(html, ticker_name):
    quote = find_quote_section(html)
    result = {}
    tick = ticker_name.lower()
    result['stock_name'] = quote.find('h2').contents[0]
    return result

>>> print parse_stock_html(html, 'GOOG')
{'stock_name': u'Google Inc. (GOOG)'}
>>> 

顺便说一句,find只需找到第一个匹配项。

>>> help(BeautifulSoup(html).find)
find(self, name=None, attrs={}, recursive=True, text=None, **kwargs) method of BeautifulSoup.BeautifulSoup instance
    Return only the first child of this Tag matching the given
    criteria.

这似乎是空的,BeautifulSoup也有findall返回所有匹配项。

>>> BeautifulSoup(html).findAll('h2')[3].contents[0]
u'Google Inc. (GOOG)'

似乎第四个值是我们正在寻找的那个......不过,我确定你没有这样做,但请不要每次都解析整个文档,这可能会非常昂贵。

于 2012-09-01T03:17:46.200 回答