python - 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
,specialties
和cities
.
所以这将是这样的:
{
doctor_name: "john hopkins",
specialty: "surgeon",
city: "new york"
}
对于我用beautifulsoup 获取的每个值。
我怎样才能做到这一点?
解决方案
以下代码将起作用。但是,它仍然不是按照您的要求做的正确方法。如果您共享要抓取的页面的 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)
使用支持性数据正确分享您的挑战将帮助我们更好地帮助您。
推荐阅读
- node.js - Nodejs如何为readline接口创建自定义方法
- python - 类定义中“...”和“通过”之间的区别?
- rapidminer - 如何在 rapidminer studio 中过滤从 phpmyadmin 中检索数据的示例?
- jenkins - Jenkins 升级到 2.212 后无法启动
- algorithm - 异步无向树中的领导者选举
- xamarin - 如何确保 Xamarin.ios 扩展项目与主项目一起部署
- oracle - 尝试访问 oracle 数据库,但触发器阻止我连接
- php - 来自自定义作曲家包的 UserProvider [Symfony 4]
- python - 如何创建代表一副纸牌的元组列表?
- gradle - 如何在报告门户上查看来自 gradle 的 TestNG 测试结果 xml 结果?