使用beautifulsoup4后如何分离报废结果?

时间:2017-11-21 03:10:35

标签: python python-3.x web-scraping beautifulsoup

我正试图从NJR中抓取数据,http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Abergele%20Hospital

我正处于获得正确值的位置,但是,我无法在各自的组中获取值。

如果您打开上面的链接,请点击“12个月的练习资料”。下拉菜单中,您可以看到不同的操作类型'。我想让每一行成为其特定的组。

截至目前,我的代码将收集所有信息,但不会将其分为特定组。实际上,在尝试更多地理解我的代码时,它只是拉动所有在其间找到的字符串,这可能不够具体。

要么我错误地提取数据,要么我需要想办法将结果分成适当的组。

import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.njrsurgeonhospitalprofile.org.uk/HospitalProfile?hospitalName=Abergele%20Hospital")
c=r.content

soup=BeautifulSoup(c,"html.parser")
all=soup.find_all(["div"],{"class":"toggle_container"})[1]
print(all)
到目前为止,我能够解析出具有所有必要数据的相应HTML代码。接下来,我遍历所有" td"对象。

i=0
for item in all.find_all("td"):
    print(all.find_all("td")[i].text)
    i=i+1
print("done")

结果:

Hip Primary
-
208
220
Hip Revision
-
Fewer Than 5
25
Knee Primary
Patello-Femoral Replacement
Fewer Than 5
4
Knee Primary
Total knee replacement
211
230
Knee Primary
Unicondylar Knee Replacement
20
26
Knee Revision
-
5
16
Shoulder Primary
-
15
16
       Total

459+
537
done

实际上,我不想要全国平均水平或总排。但是我可以稍后解决这个问题。

1 个答案:

答案 0 :(得分:1)

这可能不是解决问题的最有效方法,但您可以创建一个空列表(即all_rows),该列表将包含长度为4项的列表。

temp = list()
all_rows = list()
for item in all.find_all('td'):
    temp.append(item.text)
    i += 1
    if i % 4 == 0:
        all_rows.append(temp)
        temp = []

这给出了输出:

[
  ['Hip Primary', '-', '208', '220'],
  ['Hip Revision', '-', 'Fewer Than 5', '25'],
  ['Knee Primary', 'Patello-Femoral Replacement', 'Fewer Than 5', '4'],
  ['Knee Primary', 'Total knee replacement', '211', '230'],
  ['Knee Primary', 'Unicondylar Knee Replacement', '20', '26'],
  ['Knee Revision', '-', '5', '16'],
  ['Shoulder Primary', '-', '15', '16'],
  ['\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Total', '', '459+', '537']
]

然后你可以将所有这些存储在字典中,其中你的密钥是索引0,你的值是列表中剩余3个项目的列表。像这样:

all_rows_dict = dict()
for l in all_rows:
    all_rows_dict[l[0]] = l[1::]

这给出了输出:

{
 'Hip Primary': ['-', '208', '220'],
 'Hip Revision': ['-', 'Fewer Than 5', '25'],
 'Knee Primary': ['Unicondylar Knee Replacement', '20', '26'],
 'Knee Revision': ['-', '5', '16'],
 'Shoulder Primary': ['-', '15', '16'],
 '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0Total': ['', '459+', '537']
}

然后删除所有那些不间断的空格,你可以像这样创建一个干净的字典:

clean_dict = {key.replace(u'\xa0', u''): value for key, value in all_rows_dict.items()}

最终输出为:

{
 'Hip Primary': ['-', '208', '220'],
 'Hip Revision': ['-', 'Fewer Than 5', '25'],
 'Knee Primary': ['Unicondylar Knee Replacement', '20', '26'],
 'Knee Revision': ['-', '5', '16'],
 'Shoulder Primary': ['-', '15', '16'],
 'Total': ['', '459+', '537']
}