2016-06-10 3 views
-1

Используя приведенный ниже html, я хотел бы вытащить 2 бита данных и добавить их в список на python. каждый жирный текст - имя его лошади, а затем комментарии.Python: вычеркивание жирным шрифтом и текст, который следует

<div id="ANALYSIS" class="tabContent tabSelected">A weak handicap that looked wide open. 
 
    <br> 
 
    <br> <b class="black">LADY MAKFI</b> showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh. 
 
    She saw it out well and it´ll be interesting to see how she copes with a rise. 
 
    <br> 
 
    <br> <b class="black">Weardiditallgorong</b> went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW. 
 
    <br> 
 
    <br> <b class="black">Chauvelin</b>, in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form. 
 
    <br> 
 
    <br> <b class="black">Happy Jack</b> not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton] 
 
    <br> 
 
    <br> 
 
    <div id="resultRaceReport" class="hide"></div> 
 
</div>

из приведенного выше вывода я хотел бы, чтобы это выглядело как следующий

[LADY MAKFI, показал значительно улучшенную форму, чтобы пролить свой девичий тег на этот сезонный дебют для нового двора. В прошлом году кобыла предложила мало для Тони Мартина, но продемонстрировала некоторую способность на ее дебюте и , очевидно, способна при свежести. Она видела, как это хорошо и it'll быть интересно посмотреть, как она справляется с ростом.]

[Weardiditallgorong, пошел вниз, борьбу за эту поездку более и , вероятно, улучшился снова на своем последнее время, из второй в Ванна. Это было ее лучших усилиями еще на AW.]

[Chauvelin, во второе время шор, повернулся в его наиболее обнадеживающих усилий в течение некоторого времени, и, конечно, хорошо лечится на своей лучшей форме.]

[Счастливый Джек, не первый раз путешествовал легко, пока не сделал тяжелой погоды, когда его попросили о его усилиях. [David Orton]]

, но им просто не знает, как получить желаемый результат (больше логики позади него)

Я в настоящее время использую LXML скрести содержания и должен соответствовать полужирному (имени лошади) против моего стола, так что я могу добавить комментарии (текст после смелая) в моей базе данных

+3

Возможный дубликат [PARSING HTML с использованием Python] (http://stackoverflow.com/questions/11709079/parsing-html-using-python) –

+0

@emma Perkins, Я полагаю, вы используете lxml в соответствии с вашим предыдущим вопросом? –

+0

извинение да, я (я добавлю это в вопрос) - это больше логика на этом, а не как –

ответ

2

с использованием LXML:

h = """<div id="ANALYSIS" class="tabContent tabSelected">A weak handicap that looked wide open.<br><br> <b class="black">LADY MAKFI</b> showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh. She saw it out well and it´ll be interesting to see how she copes with a rise.<br><br> <b class="black">Weardiditallgorong</b> went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW.<br><br> <b class="black">Chauvelin</b>, in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form.<br><br> <b class="black">Happy Jack</b> not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton]<br><br> <div id="resultRaceReport" class="hide"></div></div>""" 

from lxml import html 

x = html.fromstring(h) 

div = x.xpath("//*[@id='ANALYSIS']")[0] 

# find bold tags by class name 
for b in div.xpath(".//b[@class='black']"): 
    # get bold text 
    print(b.text) 
    # get text between current bold up to next br tag. 
    print(b.xpath("./following::text()[1]")) 

даст вам:

LADY MAKFI 
[u' showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh. She saw it out well and it\xc2\xb4ll be interesting to see how she copes with a rise.'] 
Weardiditallgorong 
[' went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW.'] 
Chauvelin 
[', in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form.'] 
Happy Jack 
[' not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton]'] 

Если вы хотите, чтобы все это в одном списке точно так, как отвечал:

from lxml import html 

x = html.fromstring(h) 
div = x.xpath("//*[@id='ANALYSIS']")[0] 
out = [b.text + "," + b.xpath("./following::text()[1]")[0].lstrip(",") for b in div.xpath(".//b[@class='black']")] 

Что дает вам:

[u'LADY MAKFI, showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh. She saw it out well and it\xc2\xb4ll be interesting to see how she copes with a rise.', 
'Weardiditallgorong, went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW.', 
'Chauvelin, in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form.', 
'Happy Jack, not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton]'] 
+0

еще раз спасибо –

+0

Нет, мы можем упростить xpath, чтобы просто получить первый следующий текст после каждого жирного тега. Вы проводите анализ данных? –

+0

да - так что я собираю результаты прошлых скачек ... затем делаю анализ на них для ставок :) так что каждый комментарий на лошади должен заходить в мою базу данных и соответствовать этой лошади –

1

Я предпочитаю Beautiful Soup «s апи по сравнению с использованием LXML непосредственно. Я могу полностью исключить xpath и просто написать python.

import bs4 
soup = bs4.BeautifulSoup(document, 'lxml') 
[b.text + b.next_sibling.rstrip() for b in soup.find_all('b')] 

выход:

['LADY MAKFI showed vastly improved form to shed her maiden tag on this seasonal debut for a new yard. The filly offered little for Tony Martin last year, but did show some ability on her debut and is evidently capable when fresh.\n She saw it out well and it´ll be interesting to see how she copes with a rise.', 
'Weardiditallgorong went down fighting over this longer trip and probably improved again on her last-time-out second at Bath. This was her best effort yet on the AW.', 
'Chauvelin, in second-time blinkers, turned in his most encouraging effort for some time and is certainly well treated on his best form.', 
'Happy Jack not for the first time travelled easily until making heavy weather of it when asked for his effort. [David Orton]']