2017-02-15 2 views
0

Я извлекаю некоторые данные с веб-сайта в приведенном ниже коде, но у меня возникла проблема с продолжительностью в этой строке duration = tr.select('td.duration')[0].contents[0].strip(), которая выдает исключение ниже. Пожалуйста, как я могу исправить эту строку, спасибо вам для извлечения данных продолжительности. Я искал похожие вопросы на SO, но они не совсем отвечают на мой вопрос.Ошибка веб-скребка

# import needed libraries 
from mechanize import Browser 
from bs4 import BeautifulSoup 
import csv 

br = Browser() 

# Ignore robots.txt 
br.set_handle_robots(False) 
br.addheaders = [('User-agent', 'Chrome')] 

# Retrieve the home page 
br.open('http://fahrplan.sbb.ch/bin/query.exe/en') 
br.select_form(nr=6) 

br.form["REQ0JourneyStopsS0G"] = 'Eisenstadt' # Origin train station (From) 
br.form["REQ0JourneyStopsZ0G"] = 'sarajevo' # Destination train station (To) 
br.form["REQ0JourneyTime"] = '5:30' # Search Time 
br.form["date"] = '18.01.17' # Search Date 

# Get the search results 
br.submit() 

# get the response from mechanize Browser 
soup = BeautifulSoup(br.response().read(), 'lxml', from_encoding="utf-8") 
trs = soup.select('table.hfs_overview tr') 

# scrape the contents of the table to csv (This is not complete as I cannot write the duration column to the csv) 
with open('out.csv', 'w') as f: 
    for tr in trs: 
     locations = tr.select('td.location') 
     if len(locations) > 0: 
      location = locations[0].contents[0].strip() 
      prefix = tr.select('td.prefix')[0].contents[0].strip() 
      time = tr.select('td.time')[0].contents[0].strip() 
      duration = tr.select('td.duration')[0].contents[0].strip() 
      f.write("{},{},{},{}\n".format(location.encode('utf-8'), prefix, time, duration)) 

 

Traceback (most recent call last): 
    File "C:/.../tester.py", line 204, in <module> 
    duration = tr.select('td.duration')[0].contents[0].strip() 
IndexError: list index out of range 

Process finished with exit code 1 
+0

Вы понимаете, что означает индекс IndexError: list out of range? Ошибки довольно понятны. – Carcigenicate

+0

По внешнему виду на сайте либо нет элементов 'td', либо первый элемент' td' не содержит ничего. Отладка, чтобы узнать, что это такое. – Carcigenicate

ответ

1

Либо tr.select('td.duration') список нулевой длины или tr.select('td.duration')[0].contents список нулевой длины. Вам нужно как-то защититься от этих возможностей. Один из подходов - использовать условные обозначения.

durations = tr.select('td.duration') 
if len(durations) == 0: 
    print("oops! There aren't any durations.") 
else: 
    contents = durations[0].contents 
    if len(contents) == 0: 
     print("oops! There aren't any contents.") 
    else: 
     duration = contents[0].strip() 
     #rest of code goes here 

Или, возможно, вы хотели бы просто игнорировать регламенте, которые не соответствуют вашей ожидаемой модели, в этом случае попытка прилова может хватить.

try: 
    duration = tr.select('td.duration')[0].contents[0].strip() 
except IndexError: 
    print("Oops! tr didn't have expected tds and/or contents.") 
    continue 
#rest of code goes here 
Смежные вопросы