как я могу очистить средний контент и получить все теги h1 nad p в строках - PullRequest
0 голосов
/ 05 августа 2020

Я пытался очистить средний контент, но мне не удалось получить весь тег h1, мне удалось получить все p-теги до конца, но тег h1 отсутствует между текстом

Я хочу иметь возможность очищать весь контент в порядке появления вместе со всеми подзаголовками в теге h1

это то, что я сделал

импорт материалов

import requests
import bs4
import os
import shutil
from PIL import Image
article_URL = 'https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c' #@param {type:"string"}
# article_URL = 'https://www.tmz.com/2020/07/29/dr-dre-answers-wife-divorce-petition-prenup/'
response = requests.get(article_URL)
soup = bs4.BeautifulSoup(response.text,'html')
paragraphs = soup.find_all(['li', 'p', 'strong', 'em'])
title = soup.find(['h1','title']).get_text()
print(title)
txt_list = []
tag_list = []
with open('content2.txt', 'w') as f:
  f.write(title + '\n\n')
  for p in paragraphs:
        if p.href:
            pass
        else:
            if len(p.get_text()) > 100: # this filters out things that are most likely not part of the core article
#                 print(p.href)
                tag_list.append(p.name)
                txt_list.append(p.get_text())

txt_list2 = []
tag_list2 = []
for i in range(len(txt_list)):
#     if '\n' not in txt_list[i]:
    print(txt_list[i])
#         print(len(txt_list[i]))
#     print(tag_list[i])
    print()
    comp1 = txt_list[i].split()[0:5]
    comp2 = txt_list[i-1].split()[0:5]
    if comp1 == comp2:
        pass
    else:
        pass
        

1 Ответ

0 голосов
/ 05 августа 2020

Итак, вам нужно добавить тег h1 в список абзацев, выполнив:

paragraphs = soup.find_all(['li', 'p', 'strong', 'em', 'h1'])

Также title должен выглядеть так:

title = soup.find(['title']).get_text()

Теперь все h1 находятся в вашем списке абзацев. Вместо того, чтобы как-то сохранять их в другой массив и снова как-то сбивать их с толку, я бы просто поместил туда теги <h1>, а позже проверял, какой это тег, и выполнял другой код для разных тегов, таких как <p> или <h1>. *. 1013 *

import requests
import bs4
import os
import shutil
from PIL import Image

article_URL = 'https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c' #@param {type:"string"}

response = requests.get(article_URL)
soup = bs4.BeautifulSoup(response.text, 'html.parser')

paragraphs = soup.find_all(['li', 'p', 'strong', 'em', 'h1'])

title = soup.find(['title']).get_text()
print(title)
tag_list = []
with open('content2.txt', 'w') as f:
  f.write(title + '\n\n')
  for p in paragraphs:
        if not p.href:
            if len(p.get_text()) > 5:
                tag_list.append(p)

for i in range(len(tag_list)):
    text = tag_list[i].get_text()

    if tag_list[i].name in ["p", "li", "strong", "em"]:
        # Code run when text is in a <p> html tag
        print(f"p: {text}")
    elif tag_list[i].name in ["h1"]:
        # Code run when text is in a <h1> html tag
        print(f"h1: {text}")

Это запустит другой код для <p> и для тегов <h1> html.

...