BeautifulSoup: HTML Извлекает маркеры, но не панель навигации - PullRequest
0 голосов
/ 13 февраля 2019

Я использую BeautifulSoup4, чтобы сделать некоторую очистку HTML.Я пытаюсь извлечь важную информацию, такую ​​как заголовок, метаданные, абзацы и перечисленная информация.

Моя проблема в том, что я могу взять абзацы примерно так:

def main():
    response = urllib.request.urlopen('https://ecir2019.org/industry-day/')
    html = response.read()
    soup = BeautifulSoup(html,features="html.parser")
    text = [e.get_text() for e in soup.find_all('p')]
    article = '\n'.join(text)


    print(article)

main()

Но если ссылка на мой сайт имеет маркеры в тексте, она будет содержать панель навигации.т.е. если я изменю p на li или ul

Например, что я хочу получить в качестве вывода:

The Industry Day's objectives are three-fold:

The first objective is to present the state of the art in search and search-related areas, delivered as keynote talks by influential technical leaders from the search industry.
The second objective of the Industry Day is the presentation of interesting, novel and innovative ideas related to information retrieval.
Finally, we are looking forward to a highly-interactive discussion involving both industry and academia.

Что я на самом деле получаю: The Industry Day's objectives are three-fold:

Теги в HTML-источнике:

<p>The Industry Day's objectives are three-fold:</p>
<ol>
<li>The first objective is to present the state of the art in search and search-related areas, delivered as keynote talks by influential technical leaders from the search industry.</li>
<li>The second objective of the Industry Day is the presentation of interesting, novel and innovative ideas related to information retrieval.</li>
<li>Finally, we are looking forward to a highly-interactive discussion involving both industry and academia.</li>
</ol>

1 Ответ

0 голосов
/ 13 февраля 2019

Можно использовать синтаксис селектора Или css, чтобы можно было также выбирать элементы li.

import requests
from bs4 import BeautifulSoup

url = 'https://ecir2019.org/industry-day/'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
items = [item.text for item in soup.select('p, ol li')]

print(items)

Только этот раздел:

import requests
from bs4 import BeautifulSoup

url = 'https://ecir2019.org/industry-day/'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
items = [item.text for item in soup.select('.kg-card-markdown p:nth-of-type(2), .kg-card-markdown p:nth-of-type(2) + ol li')]

print(items)

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

import requests
from bs4 import BeautifulSoup

url = 'http://webcache.googleusercontent.com/search?q=cache:https://ecir2019.org/industry-day'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
items = [item.text for item in soup.select('.post-body p, .post-body ol li, .post-body ul li')]

print(items)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...