Форматирование текста абзаца в HTML одной строкой - PullRequest
0 голосов
/ 04 мая 2019

Я попытался извлечь текст из html-страницы, используя традиционный красивый метод супа. Я следовал коду от другого SO ответа .

import urllib
from bs4 import BeautifulSoup

url = "http://orizon-inc.com/about.aspx"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

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

результат:

\nAt Orizon, we use our extensive consulting, management, technology and\nengineering capabilities to design, develop,\ntest, deploy, and sustain business and mission-critical solutions to government\nclients worldwide.\nBy using proven management and technology deployment\npractices, we enable our clients to respond faster to opportunities,\nachieve more from their operations, and ultimately exceed\ntheir mission requirements.\nWhere\nconverge\nTechnology & Innovation\n© Copyright 2019 Orizon Inc., All Rights Reserved.\n>'

В результате возникает новая грань между технологией и \ nengineering , development, \ ntest и т. Д.

Это весь текст внутри одного абзаца.

Если мы рассмотрим его в HTML-коде, это правильно:

<p>
            At Orizon, we use our extensive consulting, management, technology and 
            engineering capabilities to design, develop, 
        test, deploy, and sustain business and mission-critical solutions to government 
            clients worldwide. 
    </p>
    <p>
            By using proven management and technology deployment 
            practices, we enable our clients to respond faster to opportunities, 
            achieve more from their operations, and ultimately exceed 
            their mission requirements.
    </p>

В чем причина этого? и как я могу извлечь его точно?

Ответы [ 2 ]

1 голос
/ 04 мая 2019

Вместо того, чтобы разбивать текст на строку, вы должны разбивать текст на тег HTML, поскольку для каждого абзаца и заголовка необходимо, чтобы текст внутри него был отделен от разрывов строк.

Это можно сделать, выполнив итерацию по всем интересующим элементам (я включил p, h2 и h1, но вы можете расширить список), и для каждого элемента уберите из него любые символы новой строки, а затем добавьте перевод строки в конец элемента, чтобы создать разрыв строки перед следующим элементом.

Вот рабочая реализация:

import urllib.request
from bs4 import BeautifulSoup

url = "http://orizon-inc.com/about.aspx"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html,'html.parser')

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# put text inside paragraphs and titles on a single line
for p in soup(['h1','h2','p']):
    p.string = " ".join(p.text.split()) + '\n'

text = soup.text
# remove duplicate newlines in the text
text = '\n\n'.join(x for x in text.splitlines() if x.strip())

print(text)

Пример вывода:

login

About Us

At Orizon, we use our extensive consulting, management, technology and engineering capabilities to design, develop, test, deploy, and sustain business and mission-critical solutions to government clients worldwide.

By using proven management and technology deployment practices, we enable our clients to respond faster to opportunities, achieve more from their operations, and ultimately exceed their mission requirements.

Если вы не хотите пробела между абзацами / заголовками, используйте:

text = '\n'.join(x for x in text.splitlines() if x.strip())
0 голосов
/ 04 мая 2019

, если вы хотите только контент из тегов абзаца, попробуйте это

paragraph = soup.find('p').getText()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...