Идея в том, чтобы проверить последние 3 страницы немецкой страницы медицинских новостей.На каждой из этих страниц есть 5 с ссылками на отдельные статьи.Программа проверяет, существует ли «href» каждого из них в файле data.csv.Если нет, он добавляет «href» в data.csv, переходит по ссылке и сохраняет содержимое в .html-файл.
содержимое каждой статьи-страницы:
<html>
..
..
<div class="newstext">
<p> article-piece 1</p>
<p> article-piece 2</p>
<p> article-piece 3</p>
<div class="URLkastenWrapper">
<div class="newsKasten URLkasten newsKastenLinks">
<p> not wanted stuff</p>
</div>
</div>
<p> article-piece 4</p>
<p> article-piece 5</p>
</div>
Я хочу сохранить «статьи-кусочки» в html и исключить «ненужные материалы».
Я пытался использовать recursive=False
, как показано в моем коде.Что касается моих исследований, то это путь к достижению моей цели, верно?
Но по какой-то причине это не работает: (
import requests
from bs4 import BeautifulSoup
import mechanicalsoup
# this requests the first 3 news-Pages; each of them contains 5 articles
scan_med_news = ['https://www.aerzteblatt.de/nachrichten/Medizin?page=1', 'https://www.aerzteblatt.de/nachrichten/Medizin?page=2', 'https://www.aerzteblatt.de/nachrichten/Medizin?page=3']
# This function is ment to create an html-file with the Article-pices of the web-site.
def article_html_create(title, url):
with open(title+'.html', 'a+') as article:
article.write('<h1>'+title+'</h1>\n\n')
subpage = BeautifulSoup(requests.get(url).text, 'html5lib')
for line in subpage.select('.newstext p', recursive=False):
#this recursive:False is not working as i wish
article.write(line.text+'<br><br>')
# this piece of code takes the URLs of allready saved articles and puts them from an .csv in a list
contentlist = []
with open('data.csv', "r") as file:
for line in file:
for item in line.strip().split(','):
contentlist.append(item)
# for every article on these pages, it checks, if the url is in the contenlist, created from the date.csv
with open('data.csv', 'a') as file:
for page in scan_med_news:
doc = requests.get(page)
doc.encoding = 'utf-8'
soup = BeautifulSoup(doc.text, 'html5lib')
for h2 in soup.find_all('h2'):
for a in h2.find_all('a',):
if a['href'] in contentlist:
# if the url is already in the list, it prints "Already existing"
print('Already existing')
else:
# if the url is not in the list, it adds the url to the date.csv and starts the article_html_create-function to save the content of the article
file.write(a['href']+',')
article_html_create(a.text, 'https://www.aerzteblatt.de'+a['href'])
print('Added to the file!')