AttributeError:'str'对象没有属性'get',实际上是字典

时间:2018-09-22 05:04:21

标签: python web-crawler

标题出现错误,您可以看到屏幕截图,实际上,名为image的变量是dict类型,但是当我使用它的方法时,它会引发错误,任何人都可以提供帮助,预先感谢。

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

1 个答案:

答案 0 :(得分:2)

如果查看输出,则不能保证image_list是字典。

  

“图片列表”:['http://abc.jpeg']

您需要正确处理各种情况。如果是列表,则将其作为列表处理。

查看此示例

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

请记住,这只能解决两个问题,您仍然需要正确处理图像本身中包含多个图像的情况。