https://ca.finance.yahoo.com/quote/TECK-B.TO/news.
Как видно, по указанному выше URL-адресу содержится более 50 статей об этой компании.
Используя Databricks и приведенный ниже код Python, мне удалось получить 2 статьи. .
Я хотел бы получить все статьи по указанному выше URL-адресу, которые были опубликованы в 2024 году.
Я пробовал использовать этот код:
Код: Выделить всё
# Install necessary libraries
# %pip install requests beautifulsoup4 pandas
import requests
from bs4 import BeautifulSoup
import pandas as pd
from pyspark.sql.types import StructType, StructField, StringType, TimestampType
from datetime import datetime
def fetch_tmx_news_2024():
url = "https://ca.finance.yahoo.com/quote/TECK-B.TO/news/"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
articles = []
for item in soup.find_all('li', class_='js-stream-content'):
link = item.find('a')['href'] if item.find('a') else None
title = item.find('a').text if item.find('a') else None
date_str = item.find('time')['datetime'] if item.find('time') else None
# Debug print to check each article's details
print(f"Title: {title}, Link: {link}, Date: {date_str}")
if date_str:
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
print(f"Parsed Date: {date}") # Debug print to check parsed date
if date.year == 2024:
articles.append({
'title': title,
'link': f"https://ca.finance.yahoo.com{link}" if link else None,
'date': date
})
# Debug print to check the articles list
print("Articles found: ", articles)
schema = StructType([
StructField("title", StringType(), nullable=True),
StructField("link", StringType(), nullable=True),
StructField("date", TimestampType(), nullable=True)
])
if articles:
return spark.createDataFrame(pd.DataFrame(articles), schema=schema)
else:
print("No articles found for the year 2024.")
return spark.createDataFrame(pd.DataFrame(columns=['title', 'link', 'date']), schema=schema)
# Invocation of the function
news_df = fetch_tmx_news_2024()
# Display Spark DataFrame
display(news_df)
Подробнее здесь: https://stackoverflow.com/questions/790 ... da-website