如何通过API/RSS获取Nasdaq Baltic网站2010年至今的TeliaLietuva AB数据并存为XML
获取TeliaLietuva AB完整新闻数据并保存为XML的方案
一、绕过RSS分页限制:直接爬取新闻列表页
由于RSS接口仅返回100条数据,直接抓取网站的新闻列表分页是更可靠的方式,步骤如下:
- 手动筛选目标内容:访问目标页面后,在「Company」下拉菜单选择「TeliaLietuva AB」,此时URL会带上筛选参数,以此作为基础请求地址。
- 分析分页逻辑:观察页面分页按钮对应的URL参数(通常是
page=1、page=2这类格式),确认分页规则。 - 循环爬取所有分页:从第1页开始,依次请求每一页内容,直到页面无新新闻或新闻日期早于2010年1月1日(新闻通常按时间倒序排列,遇到早于起始日期的内容可直接终止爬取)。
二、提取数据并生成XML文件
使用Python工具链完成数据提取与XML生成,示例代码如下:
import requests from bs4 import BeautifulSoup import xml.etree.ElementTree as ET from datetime import datetime import time # 基础请求URL(已筛选TeliaLietuva AB,替换为实际筛选后的URL) base_url = "https://nasdaqbaltic.com/statistics/en/news?company=TeliaLietuva+AB&page={}" start_date = datetime(2010, 1, 1) news_collection = [] page = 1 continue_crawling = True while continue_crawling: # 发送请求,添加UA头模拟浏览器 headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"} response = requests.get(base_url.format(page), headers=headers) if response.status_code != 200: break soup = BeautifulSoup(response.text, "html.parser") # 根据页面实际结构调整选择器,此处为示例 news_items = soup.find_all("div", class_="news-item") if not news_items: break for item in news_items: # 提取并解析发布日期 date_elem = item.find("span", class_="news-date") if not date_elem: continue date_str = date_elem.text.strip() try: news_date = datetime.strptime(date_str, "%Y-%m-%d") except ValueError: # 处理不同日期格式的情况 continue # 过滤早于2010年的新闻,终止后续爬取 if news_date < start_date: continue_crawling = False break # 提取其他新闻字段 title_elem = item.find("h3") title = title_elem.text.strip() if title_elem else "无标题" link_elem = item.find("a") link = "https://nasdaqbaltic.com" + link_elem["href"] if link_elem else "" summary_elem = item.find("p") summary = summary_elem.text.strip() if summary_elem else "" news_collection.append({ "title": title, "date": news_date.strftime("%Y-%m-%d"), "link": link, "summary": summary }) if not continue_crawling: break page += 1 time.sleep(1) # 控制请求频率,避免被封禁 # 构建XML结构 root = ET.Element("telia_news") for news in news_collection: item = ET.SubElement(root, "news_item") ET.SubElement(item, "title").text = news["title"] ET.SubElement(item, "publish_date").text = news["date"] ET.SubElement(item, "url").text = news["link"] ET.SubElement(item, "summary").text = news["summary"] # 写入XML文件 tree = ET.ElementTree(root) with open("telia_lietuva_news.xml", "wb") as f: tree.write(f, encoding="utf-8", xml_declaration=True)
关键注意事项
- 页面结构适配:代码中的HTML选择器(如
news-item、news-date)需根据网站当前实际结构调整,可通过浏览器开发者工具查看元素类名或标签。 - 反爬规避:添加合理的请求头、控制请求间隔,避免触发网站反爬机制导致IP被封禁。
- 日期格式兼容:若页面日期格式与代码中的
%Y-%m-%d不符,需修改strptime的格式参数匹配实际日期字符串。
内容的提问来源于stack exchange,提问作者jency
相关产品推荐
相关产品推荐

