标签:函数 get return xlsx 工具 orm 使用 lis 通过
import requests import pandas as pd from bs4 import BeautifulSoup import json import pandas def comments(newsurl): #获取评论信息 commentsurl = ‘http://comment5.news.sina.com.cn/page/info?version=1&format=js&channel=gn&newsid=comos-{}&group=&compress=0&ie=utf-8&oe=utf-8&page=1&page_size=20‘ x = newsurl.split(‘/‘)[-1].lstrip(‘doc-i‘).rstrip(‘.shtml‘) jd = json.loads(requests.get(commentsurl.format(x)).text.strip(‘var data=‘)) return jd[‘result‘][‘count‘][‘total‘] def getNewsDetail(newsurl): #获取新闻内容 result = {} sample = requests.get(newsurl) sample.encoding = ‘utf-8‘ soup = BeautifulSoup(sample.text,‘html.parser‘) result[‘title‘] = soup.select(‘.page-header‘)[0].text result[‘dt‘] = soup.select(‘.time-source‘)[0].contents[0].strip() result[‘article‘] = ‘ ‘.join([p.text.strip() for p in soup.select(‘#artibody p‘)[0:-1]]) result[‘resouce‘] = soup.select(‘.time-source‘)[0].contents[1].text result[‘editor‘] = soup.select(‘.article-editor‘)[0].text.lstrip(‘责任编辑:‘) result[‘comments‘] = comments(newsurl) return result def getnews(url): #获取主页面新闻连接 url.encoding=‘utf-8‘ alllist = [] soup = BeautifulSoup(url.text,‘html.parser‘) for a in soup.select(‘.news-item‘): if len(a.select(‘h2‘)) > 0: newsurl = a.select(‘a‘)[0][‘href‘] alllist.append(getNewsDetail(newsurl)) df = pandas.DataFrame(alllist) df.to_excel(‘news.xlsx‘,sheet_name=‘Random Data‘) #导出数据到excel中 url = requests.get(‘http://news.sina.com.cn/china/‘) getnews(url) #新浪国内新闻 ---------------------------------------------------------------------------------------------------------------------------------------------- 将主页面通过get方法拿到--通过BeautifulSoup进行剖析--利用开发者工具找出标题、内文、编辑、评论等信息所在位置--利用BeautifulSoup中的select方法对所需信息进行提取,并且
存入字典resul{}中--通过循环将每则新闻信息append到最后的列表alllist--使用pandas函数、DataFrame方法将列表整理,最终导出为excel表格
标签:函数 get return xlsx 工具 orm 使用 lis 通过
原文地址:http://www.cnblogs.com/missmissmiss/p/7136261.html