Я анализирую контент с помощью Python и Beautiful Soup, затем записываю его в файл CSV и столкнулся с проблемой получения определенного набора данных. Данные проходят через реализацию TidyHTML, которую я создал, а затем удаляются другие ненужные данные.
Проблема в том, что мне нужно получить все данные между набором тегов <h3>
.
Пример данных:
<h3><a href="Vol-1-pages-001.pdf">Pages 1-18</a></h3>
<ul><li>September 13 1880. First regular meeting of the faculty;
September 14 1880. Discussion of curricular matters. Students are
debarred from taking algebra until they have completed both mental
and fractional arithmetic; October 4 1880.</li><li>All members present.</li></ul>
<ul><li>Moved the faculty henceforth hold regular weekkly meetings in the
President's room of the University building; 11 October 1880. All
members present; 18 October 1880. Regular meeting 2. Moved that the
President wait on the property holders on 12th street and request
them to abate the nuisance on their property; 25 October 1880.
Moved that the senior and junior classes for rhetoricals be...</li></ul>
<h3><a href="Vol-1-pages-019.pdf">Pages 19-33</a></h3>`
Мне нужно получить все содержимое между первым закрывающим тегом </h3>
и следующим открывающим тегом <h3>
. Это не должно быть сложно, но моя тупая голова не находит нужных связей. Я могу захватить все теги <ul>
, но это не работает, потому что между тегами <h3>
и тегами <ul>
нет однозначного отношения.
Результат, которого я хочу достичь, таков:
Страницы 1-18|Vol-1-pages-001.pdf|содержимое между тегами и.
Первые две части не вызвали затруднений, но контент между набором тегов для меня сложен.
Мой текущий код выглядит следующим образом:
import glob, re, os, csv
from BeautifulSoup import BeautifulSoup
from tidylib import tidy_document
from collections import deque
html_path = 'Z:\\Applications\\MAMP\\htdocs\\uoassembly\\AssemblyRecordsVol1'
csv_path = 'Z:\\Applications\\MAMP\\htdocs\\uoassembly\\AssemblyRecordsVol1\\archiveVol1.csv'
html_cleanup = {'\r\r\n':'', '\n\n':'', '\n':'', '\r':'', '\r\r': '', '<img src="UOSymbol1.jpg" alt="" />':''}
for infile in glob.glob( os.path.join(html_path, '*.html') ):
print "current file is: " + infile
html = open(infile).read()
for i, j in html_cleanup.iteritems():
html = html.replace(i, j)
#parse cleaned up html with Beautiful Soup
soup = BeautifulSoup(html)
#print soup
html_to_csv = csv.writer(open(csv_path, 'a'), delimiter='|',
quoting=csv.QUOTE_NONE, escapechar=' ')
#retrieve the string that has the page range and file name
volume = deque()
fileName = deque()
summary = deque()
i = 0
for title in soup.findAll('a'):
if title['href'].startswith('V'):
#print title.string
volume.append(title.string)
i+=1
#print soup('a')[i]['href']
fileName.append(soup('a')[i]['href'])
#print html_to_csv
#html_to_csv.writerow([volume, fileName])
#retrieve the summary of each archive and store
#for body in soup.findAll('ul') or soup.findAll('ol'):
# summary.append(body)
for body in soup.findAll('h3'):
body.findNextSibling(text=True)
summary.append(body)
#print out each field into the csv file
for c in range(i):
pages = volume.popleft()
path = fileName.popleft()
notes = summary
if not summary:
notes = "help"
if summary:
notes = summary.popleft()
html_to_csv.writerow([pages, path, notes])
</h3>
и<h3>
. Использование sup.find всегда захватывает только первый тег h3 в документе. Есть ли способ увеличить функцию поиска супа, чтобы я мог получить все содержимое на странице между тегами<h3>
? Цикл for со счетчиком дает те же результаты, что и цикл без использования функции find. Я пробовал findAll() безуспешно, потому что он конфликтует с findNext(). 05.01.2012h3s = soup('h3'); \n for h3, h3next in zip(h3s, h3s[1:]): \n between_it = # the same as above ...
05.01.2012h3 = soup.find('h3') # find the first <h3> h3next = h3.findNext('h3') # find next <h3> h3s = soup('h3') for h3, h3next in zip(h3s, h3s[1:]): # get elements in between between_it = takewhile(lambda el: el is not h3next, h3.nextSiblingGenerator()) # extract text summary.append(''.join(getattr(el, 'text', el) for el in between_it))
06.01.2012zip()
(без аргументов). Здесь это не применимо. Код не должен производитьTypeError
. Я обновил ответ. 06.01.2012L = range(10); print zip(L, L[1:])
. Прочтите руководство по Python. Если это слишком сложно, попробуйте learnpythonthehardway.org (введите код и посмотрите результаты). 06.01.2012TypeError
и обновите свой вопрос, например,''.join([1])
а> 06.01.2012<h3>
являются одноуровневыми, в противном случае используйтеh3.nextGenerator()
). 2. Не используйтеhtml_cleanup
, используйте возможностиBeautifulSoup
для изменения html. 07.01.2012