大家好,我是python网络爬虫这门课程的主要讲师geo
url
url = "https://news.ltn.com.tw/list/breakingnews/world"
项目要爬取的内容建立于这个目标
状态码
if response.status_code != 200:
return "❌ 无法访问自由时报新闻网站。"
如果状态码不是200 则回传 “❌ 无法访问自由时报新闻网站。”
解析
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.find_all('h3')
通过BeautifulSoup解析response.text内容
去除空行
title = news.text.strip()
去掉字符串 news.text 两端的空白字符(空格、换行、制表等)
代码总结
def get_ltn_news():
url = "https://news.ltn.com.tw/list/breakingnews/world"
response = requests.get(url)
if response.status_code != 200:
return "❌ 无法访问自由时报新闻网站。"
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.find_all('h3')
news_data = ""
for news in news_list[:20]:
title = news.text.strip()
link = news.find_previous('a')['href']
news_data += f"{title}\n {link}\n\n"
return news_data if news_data else "今日无新闻更新。"
print(get_ltn_news())