首页 > 解决方案 > beautifulsoup - 多个值的多个值以及如何将它们保存到 JSON

问题描述

我正在使用 selenium + beautifulsoup。

我需要存储我找到的数据,我最初想到的是数组,但现在我认为 json 可能会更好,但我不知道如何从我抓取的内容中编写它。

        doc = []
        spec = []
        for i in range(1, 2):
            driver.get('https://local.data/doctors/%d' % i)
            driver.execute_script("$('mark').remove()")
            time.sleep(3)
            html = driver.page_source
            soup = BeautifulSoup(html, 'html.parser')
            for doctors in soup.find_all('a', attrs={"data-ga-label": "profile_name"}):
                doc.append(doctors.text)
            for specialties in soup.find_all('p', attrs={"class": "specialities"}):
                spec.append(specialties.text.strip())
            for cities in soup.find_all('span', class_="city"):
                c = cities.text.split('-')[0].replace(":", "")
                print(c)

我不想为它编写一个数组,而是为我在doctor,specialtiescities.

所以这将是这样的:

{
 doctor_name: "john hopkins",
 specialty: "surgeon",
 city: "new york"
}

对于我用beautifulsoup 获取的每个值。

我怎样才能做到这一点?

标签: pythonseleniumbeautifulsoup

解决方案


以下代码将起作用。但是,它仍然不是按照您的要求做的正确方法。如果您共享要抓取的页面的 html 结构会更好。

docs = [doctors.text for doctors in soup.find_all('a', attrs={"data-ga-label": "profile_name"})]
spec = [specialties.text.strip() for specialties in soup.find_all('p', attrs={"class": "specialities"})]
cities = [cities.text.split('-')[0].replace(":", "") for cities in soup.find_all('span', class_="city")]
doc_profiles = []
for index, data in docs:
    doc_profile ={'doctor_name': data,
                  'specialty': spec[index],
                  '': cities[index]}
    doc_profiles.append(doc_profile)

使用支持性数据正确分享您的挑战将帮助我们更好地帮助您。


推荐阅读