栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python爬取新闻标题及链接存至 Excel(含源码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python爬取新闻标题及链接存至 Excel(含源码)




新闻网址: https://www.tsinghua.edu.cn/news.htm

本片文章实现爬取新闻标题和链接

将新闻标题及链接存储至 Excel 表

源码

# 清华新闻

import pandas as pd
import requests
from lxml import etree

# 创建列表用于存储爬取的数据
list = []
# 请求网址
url = 'https://www.tsinghua.edu.cn/news.htm'
# 请求头
header = {
    'user_agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36'
}
# 获取响应 , 转为中文
response = requests.get(url=url, headers=header).content
chi = response.decode('utf-8')
# 解析html
html = etree.HTML(chi)

data = html.xpath('/html/body/div[6]/div/div/ul/li/div[3]/a')

for i in data:
    # 获取标题 , 并将标题数据加入 list 列表
    title_text = i.xpath('.//text()')[0]
    # list.append(title_text)
    # 获取url
    title_url = i.xpath('./@href')[0]
    # url 不完整,则拼接成完整url, 并将完整url 加入list列表
    if 'https' not in str(title_url):
        stitch_url = 'https://www.tsinghua.edu.cn/' + title_url
        list.append([title_text, stitch_url])
    else:
        list.append([title_text, title_url])

# 在程序运行窗口打印输出
for i in list:
    print(i)

# 持久化存储至 Excel文件
df = pd.Dataframe(list, columns=['title', 'url'])
df.to_excel("list.xlsx", index=False)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/689364.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号