thomson zeng
thomson zeng

Reputation: 11

AttributeError: 'str' object has no attribute 'get', it`s a dict,actually

There is an error as title appears, you can see the screenshot, actually, the variable named image is dict type, but when I use it`s method, it throws an error, any one can help, thanks in advance.

import requests, os
from urllib.parse import urlencode
from multiprocessing.pool import Pool
def get_page(offset):
    params = {
        'offset': offset,
        'format': 'json',
        'keyword': '街拍',
        'autoload': 'true',
        'count': '20',
        'cur_tab': '1'
    }
    url = 'http://www.toutiao.com/search_content/?' + urlencode(params)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.json()
    except requests.ConnectionError:
        return None

def get_images(json):
    if json.get('data'):
        for item in json.get('data'):
            title = item.get('title')
            images = item.get('image_list')
            print('images type:', type(images))
            for image in images:
                print('image type:',type(image),image)
                http_url = 'http:' + image.get('url')
                results = {
                    'image': http_url,
                    'title': title
                }
                yield results
            # yield {'title': title}

def main(offset):
    json = get_page(offset)
    for item in get_images(json):
        print(item)

GROUP_START = 1
GROUP_END = 20
if __name__ == '__main__':
    pool = Pool()
    groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
    pool.map(main, groups)
    pool.close()
    pool.join()

screenshot about the result after execution

Upvotes: 0

Views: 1367

Answers (1)

eandersson
eandersson

Reputation: 26342

If you look at the output it's not guaranteed that image_list is a dictionary.

'image_list': ['http://abc.jpeg']

You need to properly handle the various scenarios. If it's a list just handle it as a list.

See this example

def get_images(json):
    if not json.get('data'):
        return
    for item in json.get('data'):
        title = item.get('title')
        images = item.get('image_list')

        if not images: # This can be None as well. If so, just skip.
            continue

        print('images type:', type(images))
        for image in images:
            if not image:
                continue
            print('image type:',type(image),image)
            if isinstance(image, dict):
                im = image.get('url')
            else:
                im = image[0] # You should probably iterate this list.
            http_url = 'http:' + im
            results = {
                'image': http_url,
                'title': title
            }
            yield results

Keep in mind that this only solves two of the problems, you still need to properly handle cases where there are multiples images within image itself.

Upvotes: 2

Related Questions