2014-12-10 2 views
-1

Я пытаюсь создать простой искатель, который извлекает метаданные с веб-сайтов и сохраняет информацию в csv. До сих пор я застрял здесь, я следил за некоторыми гидами, но теперь я застрял с ошибкой:Python BS4 crawler indexerror

IndexError: список индексов за пределами допустимого диапазона.

from urllib import urlopen 
from BeautifulSoup import BeautifulSoup 
import re 

# Copy all of the content from the provided web page 
webpage = urlopen('http://www.tidyawaytoday.co.uk/').read() 

# Grab everything that lies between the title tags using a REGEX 
patFinderTitle = re.compile('<title>(.*)</title>') 

# Grab the link to the original article using a REGEX 
patFinderLink = re.compile('<link rel.*href="(.*)" />') 

# Store all of the titles and links found in 2 lists 
findPatTitle = re.findall(patFinderTitle,webpage) 
findPatLink = re.findall(patFinderLink,webpage) 

# Create an iterator that will cycle through the first 16 articles and skip a few 
listIterator = [] 
listIterator[:] = range(2,16) 

# Print out the results to screen 
for i in listIterator: 
    print findPatTitle[i] # The title 
    print findPatLink[i] # The link to the original article 

articlePage = urlopen(findPatLink[i]).read() # Grab all of the content from original article 

divBegin = articlePage.find('<div>') # Locate the div provided 
article = articlePage[divBegin:(divBegin+1000)] # Copy the first 1000 characters after the div 

# Pass the article to the Beautiful Soup Module 
soup = BeautifulSoup(article) 

# Tell Beautiful Soup to locate all of the p tags and store them in a list 
paragList = soup.findAll('p') 

# Print all of the paragraphs to screen 
for i in paragList: 
    print i 
    print '\n' 

# Here I retrieve and print to screen the titles and links with just Beautiful Soup 
soup2 = BeautifulSoup(webpage) 

print soup2.findAll('title') 
print soup2.findAll('link') 

titleSoup = soup2.findAll('title') 
linkSoup = soup2.findAll('link') 

for i in listIterator: 
    print titleSoup[i] 
    print linkSoup[i] 
    print '\n' 

Любая помощь была бы принята с благодарностью.

Ошибки я получаю

File "C:\Users......", line 24, in (module) 
    print findPatTitle[i] # the title 
IndexError:list of index out of range 

Спасибо.

+0

Не могли бы вы сузить это до *, где именно * вы получите ошибку? При абсолютном минимуме полная трассировка была бы намного более полезной, чем только последняя строка. Пожалуйста, прочитайте http://stackoverflow.com/help/mcve – jonrsharpe

+0

, отредактированный, спасибо. – BubblewrapBeast

+0

Итак, что такое значение 'i', и что (если что-либо) находится в' findPatTitle'? – jonrsharpe

ответ

0

Кажется, что вы не используете всю мощь, которую может дать вам bs4.

Вы получаете эту ошибку, потому что длина patFinderTitle является только одной, так как у всех html обычно есть только один элемент заголовка для каждого документа.

Простой способ, чтобы захватить титул HTML, использует BS4 себя:

from bs4 import BeautifulSoup 
from urllib import urlopen 

webpage = urlopen('http://www.tidyawaytoday.co.uk/').read() 
soup = BeautifulSoup(webpage) 

# get the content of title 
title = soup.title.text 

Вы, вероятно, получите ту же самую ошибку, если вы попытаетесь итерацию над findPatLink в настоящее время способом, так как он имеет длина 6. для меня, это не достаточно ясно, если вы хотите, чтобы получить все элементы ссылок или все элементы анкерных, но stickying с первой идеей, вы можете улучшить свой код, используя BS4 снова:

link_href_list = [link['href'] for link in soup.find_all("link")] 

И наконец, поскольку вам не нужны некоторые URL-адреса, вы можете отрезать link_href_list в том виде, в котором вы хотите. Улучшенная версия последнего выражения, исключающая первый и второй результаты, может быть:

link_href_list = [link['href'] for link in soup.find_all("link")[2:]]