1

I am writing a web scraper that gets a car_id and all of its images:

car_id = 12345
images = []
image_list = self.driver.find_elements_by_css_selector('.carousel-inner a img')
for img in image_list:
 img_url = img.get_attribute('src')
 if img_url:
 images.append(img_url)

The output of the program is a json object, containing car_id and a list of its images... but how do I serialize the python array into the following json object?

item = {
 'car_id': car_id,
 'images': ["img1", "img2", ...] # serialize images array 
}
asked Feb 27, 2021 at 7:33

2 Answers 2

1
car_id = 12345
images = ['url1', 'url2', 'url3'] #list of image urls
item = {
 'car_id' : car_id,
 'images' : images
}

The item dict can be edited using

item['images'].append('url4')

If instead the images list has actual image objects (serialized into bytes or some other format), then the images list can contain those objects.

The variable item will be of type dict in python. This may be sufficient for your use case. If not then you may want to convert it to json string.

import json
result = json.dumps(item)

result will have the required json string.

answered Feb 27, 2021 at 7:43
Sign up to request clarification or add additional context in comments.

Comments

1

initialize the item then use item['images'].append(img_url)

items = []
for id in listID:
 item = {
 "car_id": id, # 12345
 "images" = []
 }
 
 image_list = self.driver.find_elements_by_css_selector('.carousel-inner a img')
 for img in image_list:
 img_url = img.get_attribute('src')
 if img_url:
 item['images'].append(img_url)
 
 items.append(item)
 
print(items)
'''
[{
 'car_id': 12,
 'images': ["img1", "img2", ...] 
},
{
 'car_id': 23,
 'images': ["img1", "img2", ...]
}]
'''
answered Feb 27, 2021 at 8:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.