-1

I'm new to Python and trying to generate a list of dictionaries in JSON format. I get the data from Selenium by iterating through an element. I get the output as string. Here's my selenium snippet:

Company = driver.find_elements_by_xpath("//*[@class='au-target company']")
Category = driver.find_elements_by_xpath("//*[@class='job-category']")

I get my data by using a for loop like this:

for value in Company:
    print(value.text)

for value in Category:
    print(value.text)

Here are my results:

Company A
Company B
Company C
Digital Technology
Manufacturing
Supply Chain

I would like to have my data in the following format

[
    {
        "Company": "Company A",
        "Category": "Digital Technology"
    },
    {
        "Company": "Company B",
        "Category": "Manufacturing"
    },
    {
        "Company": "Company C",
        "Category": "Supply Chain"
    }
]

So far I have been unsuccessful using the json module. Thanks!

2

2 Answers 2

1

You can handle it like this

d = []
for company, category in zip(Company, Category):
    d.append({
        "company": company.text,
        "category": category.text
    })

or

d = [
    {"company": company.text, "category": category.text}
    for company, category in zip(Company, Category)
]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've gone with your first suggestion, worked like a charm!
0

Try this,

data = []
for comp, cat in zip(Company, Category):
    data.append({'Company':comp, 'Category': cat})

Output:

data
[
    {
        "Company": "Company A",
        "Category": "Digital Technology"
    },
    {
        "Company": "Company B",
        "Category": "Manufacturing"
    },
    {
        "Company": "Company C",
        "Category": "Supply Chain"
    }
]

Comments

Your Answer

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.