2014-11-18 5 views
0

Я пытаюсь очистить этот сайт, но я все время получаю ошибку, когда пытаюсь распечатать только содержимое таблицы.Python: содержимое таблицы html

soup = BeautifulSoup(urllib2.urlopen('http://clinicaltrials.gov/show/NCT01718158 
').read()) 

print soup('table')[6].prettify() 


for row in soup('table')[6].findAll('tr'): 
    tds = row('td') 
    print tds[0].string,tds[1].string 

IndexError        Traceback (most recent call last) 
<ipython-input-70-da84e74ab3b1> in <module>() 
    1 for row in soup('table')[6].findAll('tr'): 
    2  tds = row('td') 
    3  print tds[0].string,tds[1].string 
    4 

IndexError: list index out of range 

ответ

1

Таблица имеет строку заголовка, с <th> элементов заголовка, а не <td> клеток. В вашем коде предполагается, что в каждой строке всегда будет <td> элементов, а для первой строки это не получается.

Вы можете пропустить строку с не достаточно <td> элементов:

for row in soup('table')[6].findAll('tr'): 
    tds = row('td') 
    if len(tds) < 2: 
     continue 
    print tds[0].string, tds[1].string 

в какой момент вы получите выход:

>>> for row in soup('table')[6].findAll('tr'): 
...  tds = row('td') 
...  if len(tds) < 2: 
...   continue 
...  print tds[0].string, tds[1].string 
... 
Responsible Party: Bristol-Myers Squibb 
ClinicalTrials.gov Identifier: None 
Other Study ID Numbers: AI452-021, 2011‐005409‐65 
Study First Received: October 29, 2012 
Last Updated: November 7, 2014 
Health Authority: None 

Последняя строка содержит текст с вкраплениями <br/> элементов; вы можете использовать генератор element.strings для извлечения всех строк и, возможно, объединения их в новые строки; Я бы разделил каждую строку сначала:

>>> for row in soup('table')[6].findAll('tr'): 
...  tds = row('td') 
...  if len(tds) < 2: 
...   continue 
...  print tds[0].string, '\n'.join(filter(unicode.strip, tds[1].strings)) 
... 
Responsible Party: Bristol-Myers Squibb 
ClinicalTrials.gov Identifier: NCT01718158 
History of Changes 
Other Study ID Numbers: AI452-021, 2011‐005409‐65 
Study First Received: October 29, 2012 
Last Updated: November 7, 2014 
Health Authority: United States: Institutional Review Board 
United States: Food and Drug Administration 
Argentina: Administracion Nacional de Medicamentos, Alimentos y Tecnologia Medica 
France: Afssaps - Agence française de sécurité sanitaire des produits de santé (Saint-Denis) 
Germany: Federal Institute for Drugs and Medical Devices 
Germany: Ministry of Health 
Israel: Israeli Health Ministry Pharmaceutical Administration 
Israel: Ministry of Health 
Italy: Ministry of Health 
Italy: National Bioethics Committee 
Italy: National Institute of Health 
Italy: National Monitoring Centre for Clinical Trials - Ministry of Health 
Italy: The Italian Medicines Agency 
Japan: Pharmaceuticals and Medical Devices Agency 
Japan: Ministry of Health, Labor and Welfare 
Korea: Food and Drug Administration 
Poland: National Institute of Medicines 
Poland: Ministry of Health 
Poland: Ministry of Science and Higher Education 
Poland: Office for Registration of Medicinal Products, Medical Devices and Biocidal Products 
Russia: FSI Scientific Center of Expertise of Medical Application 
Russia: Ethics Committee 
Russia: Ministry of Health of the Russian Federation 
Spain: Spanish Agency of Medicines 
Taiwan: Department of Health 
Taiwan: National Bureau of Controlled Drugs 
United Kingdom: Medicines and Healthcare Products Regulatory Agency 
+0

MARTIJN! ВЫ «БОГ» С МАЛЫМ «g». Бесконечно благодарен. –

+0

Martijn, как мне получить содержимое таблицы, предшествующее этому: «Показать 77 учебных мест» на странице: «http://clinicaltrials.gov/show/NCT01718158». Это таблица, я не знаю, почему я не могу ее найти, когда у меня есть: table [variable]. Благодарю. –