属性错误:'str'对象没有属性"get",它是一个字典,实际上



标题出现错误,您可以看到屏幕截图,实际上,名为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()

关于执行后结果的屏幕截图

如果你看一下输出,不能保证image_list是字典。

"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

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

最新更新