简体   繁体   中英

Tuple object has no attribute text

I am writing a code to get specific information from yahoo finance website

    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

Where %s is a name of a stock. If I manually input a name of a stock everything works great. But if I try to run a for loop for a list that I made,

    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

I get an error on tree line 'tuple' object has no attribute 'text'

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

This is not how to define a format string. You accidentally created a tuple ('http://finance.yahoo.com/q/pr?s=%s', x)

To incorporate x into the string write it like this:

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

Or even better because not needing specifiers:

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

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

Your mistake is:

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

Instead of formatting the string, you made 'page' a tuple. This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM