Написал новостной парсер на Python, не могу подключить БД mySQL
Написал парсер на Python, не могу подключить БД mySQL. Необходимо чтобы, результат парсера забивал в базу, заголовок, ссылка, время. Нужна помощь срочно.
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
url = "https://www.nur.kz/latest/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
articles_cards = soup.find_all("a", class_="article-preview-category__content")
for article in articles_cards:
article_title = article.find("h2", class_="article-preview-category__subhead").text.strip()
#article_desc = article.find("p").text.strip()
article_url = f'{article.get("href")}'
article_date_time = article.find("time").get("datetime")
date_from_iso = datetime.fromisoformat(article_date_time)
date_time = datetime.strftime(date_from_iso, "%Y-%m-%d %H:%M:%S")
article_date_timestamp = time.mktime(datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S").timetuple())
print(article_title,"|||", article_url, '|||', article_date_timestamp)
Ответы (1 шт):
Автор решения: RB180
→ Ссылка
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
url = "https://www.nur.kz/latest/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
articles_cards = soup.find_all("a", class_="article-preview-category__content")
#news_dict = {}
for article in articles_cards:
article_title = article.find("h2", class_="article-preview-category__subhead").text.strip()
#article_desc = article.find("p").text.strip()
article_url = f'{article.get("href")}'
article_date_time = article.find("time").get("datetime")
date_from_iso = datetime.fromisoformat(article_date_time)
date_time = datetime.strftime(date_from_iso, "%Y-%m-%d %H:%M:%S")
article_date_timestamp = time.mktime(datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S").timetuple())
#print(article_title,"|||", article_url, '|||', article_date_timestamp)
#Подключился к базе
db = mysql.connector.connect(host='localhost',
user='root',
password='',
db='testdb123',
charset='utf8',
autocommit=True)
print ("connect successful!!")
cursor = db.cursor()
url = 'https://www.nur.kz/latest/'
array = get_data(get_html(url))
sqlFormula = "INSERT INTO users (`article_title`, `article_url`, `article_date_timestamp`) VALUES (%s,%s,%s)"
cursor=mydb.cursor()
mycursor.executemany(sqlFormula,(str(article_title)),str(article_url),str(article_date_timestamp))
mydb.commit()