python:爬取新浪新闻的内容

本文介绍了一种使用Python爬取新浪新闻网站上新闻详情及评论数据的方法,包括新闻标题、日期、来源、内容、编辑及评论数的提取,并将数据整理成Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import requests
import json
from bs4 import BeautifulSoup
import re
import pandas
import sqlite3


commenturl='https://comment.sina.com.cn/page/info?version=1&format=json' \
           '&channel=gn&newsid=comos-{}&group=undefined&compress=0&' \
           'ie=utf-8&oe=utf-8&page=1&page_size=3&t_size=3&h_size=3&thread' \
           '=1&callback=jsonp_1543748934208'
# 获取评论数
def getCommentCounts(newsurl):
    #获取没则新闻的编号(正则表达式)
    m = re.search('doc-i(.*).shtml', newsurl)
    newsid = m.group(1)
    #格式化链接中的的大括号
    comments = requests.get(commenturl.format(newsid))
    #把加了js外套的json变成标准json
    jd = json.loads(comments.text.strip('jsonp_1543748934208()'))
    #获取评论数
    return jd['result']['count']['total'];

# 提取每则新闻的内文
def getNewsDetail(newsurl):
    # 定义一个字典存储信息
    result = {}
    rsp = requests.get(newsurl)
    rsp.encoding = 'utf-8'
    soup = BeautifulSoup(rsp.text,'html.parser')
    # 获取标题
    result['title'] = soup.select('.main-title')[0].text
    # 获取日期
    result['time'] = soup.select('.date')[0].text
    # 获取来源
    result['source'] = soup.select('.source')[0].text
    # 获取内容
    result['article'] = ' '.join([p.text.strip() for p in soup.select('#article p')[:-1]])
    # 获取编辑
    result['editor'] = soup.select('.show_author')[0].text.lstrip('责任编辑:')
    # 获取评论数
    result['comment']=getCommentCounts(newsurl)
    return result

# 获取分页链接
def parseListLinks(url):
    newsdetails = []
    rsp = requests.get(url)
    # 把加了js外套的json变成标准json
    jsonUrl = '{' + str(rsp.text.lstrip('try{feedCardJsonpCallback(').rstrip(') ;}catch(e){};')) + '}}'
    jd=json.loads(jsonUrl)
    # 获取每页的新闻链接
    for ent in jd['result']['data']:
        newsdetails.append(getNewsDetail(ent['url']))
    return newsdetails

url='https://feed.sina.com.cn/api/roll/' \
    'get?pageid=121&lid=1356&num=20&versionNumber=1.2.4' \
    '&page={}&encode=utf-8&callback=feedCardJsonpCallback&_'
news_total = []
for i in range(1,3):#爬取的页数自己设定
    # 格式化链接中的大括号
    newsurl = url.format(i)
    newsary = parseListLinks(newsurl)
    news_total.extend(newsary)
# 使用pandas模块使爬取到的信息格式化
df = pandas.DataFrame(news_total)
# 保存为xlsx文件
df.to_excel('news.xlsx')

 

好的,这个问题需要用到Python的爬虫技术,具体步骤如下: 1. 导入必要的库 先导入requests、BeautifulSoup库,来实现网页的请求和解析。 ```python import requests from bs4 import BeautifulSoup ``` 2. 确定爬取网站和页面 我们需要爬取新浪、网易、今日头条、UC四大网站新闻标题和内容,因此需要确定每个网站新闻页面的URL。 以新浪为例,它的新闻页面URL为:https://news.sina.com.cn/china/,我们需要爬取这个页面上的所有新闻标题和内容。 3. 发送请求并解析页面 使用requests库发送请求,获取新浪新闻页面的HTML源码,然后使用BeautifulSoup库解析HTML源码,得到新闻标题和内容。 ```python url = 'https://news.sina.com.cn/china/' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') ``` 4. 提取新闻标题和内容 使用BeautifulSoup库提取新闻标题和内容。 ```python # 提取新闻标题 titles = soup.select('.news-item h2 a') for title in titles: print(title.text) # 提取新闻内容 contents = soup.select('.news-item p') for content in contents: print(content.text) ``` 5. 爬取其他网站 对于其他网站,只需要重复上述步骤即可,只需要修改URL和CSS选择器即可。 完整代码如下: ```python import requests from bs4 import BeautifulSoup # 爬取新浪新闻 url = 'https://news.sina.com.cn/china/' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') # 提取新闻标题 titles = soup.select('.news-item h2 a') for title in titles: print(title.text) # 提取新闻内容 contents = soup.select('.news-item p') for content in contents: print(content.text) # 爬取网易新闻 url = 'https://news.163.com/' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') # 提取新闻标题 titles = soup.select('.item-top a') for title in titles: print(title.text) # 提取新闻内容 contents = soup.select('.item-wrap p') for content in contents: print(content.text) # 爬取今日头条新闻 url = 'https://www.toutiao.com/ch/news_hot/' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') # 提取新闻标题 titles = soup.select('.title-box a') for title in titles: print(title.text) # 提取新闻内容 contents = soup.select('.abstract') for content in contents: print(content.text) # 爬取UC新闻 url = 'https://news.uc.cn/' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') # 提取新闻标题 titles = soup.select('.item-title a') for title in titles: print(title.text) # 提取新闻内容 contents = soup.select('.item-desc') for content in contents: print(content.text) ``` 注意:在实际使用中要注意网站的反爬机制,避免被封IP。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值