2015-09-15 85 views
1

我寫一個代碼從雅虎財經網站元組對象沒有屬性文字

page = requests.get('http://finance.yahoo.com/q/pr?s=%s') 
    tree=html.fromstring(page.text) 
    annual_report = tree.xpath('//td[@class="yfnc_datamoddata1"]/text()') 
    annual_report 

%s是股票的名稱得到具體的信息。如果我手動輸入股票的名稱,一切都很好。但是,如果我試圖for循環,我做了一個列表運行,

for x in my_list: 
     page = requests.get('http://finance.yahoo.com/q/pr?s=%s'),(x,) 
     tree=html.fromstring(page.text) 
     annual_report = tree.xpath('//td[@class="yfnc_datamoddata1"]/text()') 
     print annual_report 

我得到一個錯誤的樹行'tuple' object has no attribute 'text'

回答

1

你的錯誤是:

page = requests.get('http://finance.yahoo.com/q/pr?s=%s'),(x,) 

格式化字符串,而不是你做 '頁面' 的元組。 這應該工作:

page = requests.get('http://finance.yahoo.com/q/pr?s=%s' % (x,)) 
+0

謝謝。這工作。 – AK9309

1

page = requests.get('http://finance.yahoo.com/q/pr?s=%s'),(x,)

這不是如何定義一個格式字符串。你一不小心創造了一個元組('http://finance.yahoo.com/q/pr?s=%s', x)

要合併x到字符串它這樣寫:

page = requests.get('http://finance.yahoo.com/q/pr?s=%s' % x)

甚至更​​好,因爲不需要符:

  • page = requests.get('http://finance.yahoo.com/q/pr?s={0}'.format(x))

  • page = requests.get('http://finance.yahoo.com/q/pr?s=' + x)

+0

謝謝你的解釋 – AK9309

相關問題