Webdriver 爬取新浪滚动新闻

初始想法

本人现在是国际关系学院2016级的本科生,学的是信息管理与信息系统。讲道理不知道这个专业到底是干啥的,现在选择的后续方向是数据科学与工程,并且在老师的自然语言处理小组。爬虫是做自然语言处理的基础嘛,学习机器学习之前先学学怎么爬取内容还是挺有意义的。本来开始想着爬一下新浪微博的内容,但是又涉及到滚动爬取,账号登陆之类的繁琐问题,还是先玩玩滚动新闻吧。其实讲道理中国新闻网的滚动新闻做的比新浪的好多了,界面也好看,不过这都是爬完之后才发现的哈哈哈哈哈哈哈

背景介绍

本项目为基于新浪滚动新闻(https://news.sina.com.cn/roll/#pageid=153&lid=2509&k=&num=50&page=1)进行网页爬取,以新闻标题为文件名称,以新闻内容为文件正文存储。

内容介绍

环境要求

  • 环境要求:python3.7+
  • 安装包要求:time,requests,random,Beautifulsoup,selenium等

文件介绍

  • main:调取其他所有文件相关函数,输入初始url,并计算爬取全部网页耗时
  • date_helper:对网页日期进行调整实现自动翻页
  • data_helper:对数据的所有路径进行调整
  • spider:爬取网页的主文件,调用Webdriver获取主索引页的子页面并获取网页内容
  • article_spider:爬取新闻正文内容

代码

main

from date_helper import date_processing
from data_helper import pickle_writer
from spider import *
import timestart = time.clock()
if __name__ == '__main__':url_org = 'http://roll.news.sina.com.cn/s/channel.php?ch=01#col=89&spec=&type=&date={}&ch=01&k=&offset_page=0&offset_num=0&num=60&asc=&page='while True:date = date_processing()  # 获取日期output_list = []          # 存放输出序列 listurl = url_org.format(date) # 生成待爬取URLsina(url,output_list,date) # 爬虫print(output_list)print(len(output_list))file_name = ''.format(date)pickle_writer(output_list, file_name)  # 写入临时文件存放
end = time.clock()
print('Running:%s seconds.'%(end - start))

date_helper

from selenium import webdriver
import re
import time
import calendar
import re
import codecs
from data_helper import *def count_days(year, month):cal = calendar.monthrange(year, month)pattern = re.compile(r'\d+')days = pattern.findall(str(cal))[1]return daysdef month_sub(year,month):if month > 10:month -= 1month = str(month)elif month <= 10 and month > 1 :month -= 1month = '0'+str(month)else:year -= 1month = 12return year,monthdef date_sub(year,month,day):if day > 10:day -= 1day = str(day)elif day <= 10 and day > 1:day -= 1day = '0'+str(day)else:year, month = month_sub(int(year),int(month))days = count_days(year, int(month))day = daysdate = str(year)+'-'+str(month) +'-'+str(day)  #新浪滚动新闻return datedef date_processing():date_txt = ""last_date = txt_load(date_txt)date = str(last_date[0])year = int(date.split("-")[0])month = date.split("-")[1]day = int(date.split("-")[2])date = date_sub(year, month, day)writer = codecs.open(date_txt,'w','UTF-8')writer.write(date)writer.flush()return date

data_helper

import re
import pickle
import codecs
import jieba
'''
读取原始数据
'''
def txt_load(path):reader = codecs.open(path,'r','UTF-8')lines = reader.readlines()return linesdef join_list(ss):c = ""for k in ss:c+=kreturn cdef pickle_writer(input_,name):''':param input_: 待保存的数据:param name:  存放路径'''writer = open(name,"wb")pickle.dump(input_,writer)writer.close()print("finish to write data")# 定义读plk文件函数
def pickle_load(input_):''':param input_: 路径:return:  原始数据'''raeder = open(input_,"rb")content = pickle.load(raeder)raeder.close()print("finish to read data")return contentdef jieba_cut(content):''':param content: str 句子 待分词:return: 分好词的list'''cut = jieba.cut(content)l = []for con in cut:if con!=" ":l.append(con)return ldef is_chinese(uchar):"""判断一个unicode是否是汉字"""if uchar >= u'\u4e00' and uchar <= u'\u9fa5':return ucharelif uchar == re.sub('[^a-zA-Z]', '', uchar):return str(uchar).lower()else:return ''

spider

# -*- coding: utf-8 -*-from selenium import webdriver
from article_spider import *
import redef get_pages(driver,url):''':param driver: Webdriver页面:param url: 指定日期的链接:return page_num: 指定日期内页面的数量'''start_url = url + '1'driver.get(start_url)time.sleep(2)driver.refresh()time.sleep(2)page_html = driver.page_sourcepagelist = re.findall('onclick="newsList.page.goTo(.*?);return false', page_html, re.S)pattern = re.compile('\d+')  # 获取页码数page_num = pattern.findall(pagelist[len(pagelist)-1])[0]return (page_num)def Get_content(driver,page_num,url,output_list,date):''':param driver: Webdriver页面:param page_num: 指定日期内页面的数量:param url: 指定日期的链接:param output_list: 输出list :param date: 指定日期'''k = 1while k <= int(page_num):driver.get(url + str(k))time.sleep(2.5)driver.refresh()for i in range(1, 11):for j in range(1, 6):classfy_cn = driver.find_element_by_xpath('//*[@id="d_list"]/ul[' + str(i) + ']/li[' + str(j) + ']/span[1]').texttitle = driver.find_element_by_xpath('//*[@id="d_list"]/ul[' + str(i) + ']/li[' + str(j) + ']/span[2]/a').texthref = driver.find_element_by_xpath('//*[@id="d_list"]/ul[' + str(i) + ']/li[' + str(j) + ']/span[2]/a').get_attribute('href')times = driver.find_element_by_xpath('//*[@id="d_list"]/ul[' + str(i) + ']/li[' + str(j) + ']/span[3]').textpubtime = times.split(" ")[1]content, classfy_en = get_article(href)content_list = [classfy_cn, classfy_en, date, pubtime, title, href, content]test = '' + title + '.txt'with open(test, 'w') as f:for content_list_element in content_list:f.write(content_list_element)output_list.append(content_list)print(len(output_list))k = k + 1def sina(url,output_list,date):''':param url: 待爬取的url:param output_list: 输出list:param date: 日期:return:'''driver = webdriver.Chrome()page_num = get_pages(driver, url)Get_content(driver, page_num, url, output_list, date)driver.close()

article_spider

#-*- coding:utf-8 -*-from bs4 import BeautifulSoup
from user_agents import agents
import requests
import time
import randomdef get_article(url):''':param url: 指定日期的链接:return content: 文本的内容:return classfy: 文本的类型'''try:classfy = url.split('.')[0].split('//')[1]agent = random.choice(agents)header = {'User-Agent': agent}res = requests.get(url.rsplit('\r\n')[0], headers=header)time.sleep(1)res.encoding = 'utf-8'soup = BeautifulSoup(res.text, 'html.parser')newsArticle = getnewsArticle(soup.select('.art_p'))content = ''for con in newsArticle:content = content + conreturn content, classfyexcept Exception as e:print(e)def getnewsArticle(news):''':param news: 新闻主题内容链接:return newsArticle: 新闻主题内容'''newsArticle = []for p in news:newsArticle.append(p.text.strip())return newsArticle

后记

爬取下来的内容还算ok,虽然这样看起来又繁琐又蛋疼,而且好像如果新闻标题中含有" / "这个字符的话,就会报错,显示没有这个文件夹,或许第二版代码我再考虑怎么加一下中文匹配(?)。代码里面的agent就随便网上找点就行,不用太在意。
第一次写,想来也有很多很多毛病,如果有人看到,还请指出,感恩的心,感谢有你。

Webdriver 爬取新浪滚动新闻相关推荐

  1. Python 爬虫实例(7)—— 爬取 新浪军事新闻

    我们打开新浪新闻,看到页面如下,首先去爬取一级 url,图片中蓝色圆圈部分 第二zh张图片,显示需要分页, 源代码: # coding:utf-8import json import redis im ...

  2. 爬取新浪社会新闻源代码

    视频地址如下: https://edu.hellobi.com/course/81/play/lesson/1761 import requests from bs4 import Beautiful ...

  3. python3爬取新浪NBA新闻信息(待完善)

    #!/usr/bin/env python # -*- coding: utf-8 -*- import requests from requests.exceptions import ReadTi ...

  4. 从入门到入土:Python爬虫学习|实例练手|爬取新浪新闻搜索指定内容|Xpath定位标签爬取|代码注释详解

    此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...

  5. requests, Beautifusoup 爬取新浪新闻资讯

    ###1.爬取新浪新闻首页的新闻标题时间和链接 1 import requests 2 from bs4 import BeautifulSoup 3 4 res = requests.get('ht ...

  6. python爬虫scrapy爬取新闻标题及链接_18Python爬虫---CrawlSpider自动爬取新浪新闻网页标题和链接...

    一.爬取新浪新闻思路 1.创建scrapy项目 2.分析新浪新闻网站静态页面代码 3.编写对应的xpath公式 4.写代码 二.项目代码 步骤1.创建scrapy项目 scrapy startproj ...

  7. 19Python爬虫--爬取新浪新闻标题并保存到数据库

    一.爬取新浪新闻思路 1.创建scrapy项目 2.分析新浪新闻网站静态页面代码 3.编写对应的xpath公式 4.写代码 二.项目代码 步骤1.创建scrapy项目 创建爬虫文件 scrapy st ...

  8. python爬取新浪新闻

    最近公司项目比较少,楼主闲了好长时间了,作为一个刚毕业几个月的新人,心里很烦躁,只能自己找点新东西去学了.看到周围好多人都接触了爬虫,再加上楼主最近沉迷吴宣仪不可自拔,每天投票投票,投票的同时需要监控 ...

  9. 网络爬虫-----python爬取新浪新闻

    思路:先爬取首页,然后通过正则筛选出所有文章url,然后通过循环分别爬取这些url到本地 #python新闻爬虫实战 import urllib.request import re url = 'ht ...

  10. Python3:爬取新浪、网易、今日头条、UC四大网站新闻标题及内容

    Python3:爬取新浪.网易.今日头条.UC四大网站新闻标题及内容 以爬取相应网站的社会新闻内容为例: 一.新浪: 新浪网的新闻比较好爬取,我是用BeautifulSoup直接解析的,它并没有使用J ...

最新文章

  1. LinkedIn 开源成功的秘密
  2. 纯css3鼠标经过出现文字或图片鼠标移走消失
  3. SVN钩子--hook
  4. java代码示例(6-3)
  5. JAXB做错了; 尝试Xembly
  6. OJ1080: a+b(多实例测试3)(C语言)
  7. 使用-辗转相除法-求最大公约数
  8. 大数据的“媒体玩法”
  9. uri uri_什么是URI? 了解许可证术语以确保合规
  10. python pep8_Python 代码风格 和 PEP8
  11. 【转】查看linux服务器的系统信息
  12. 因果推断——借微软EconML测试用DML和deepIV进行反事实预测实验(二十五)
  13. 大疆飞行模拟(DJI Flight Simulator)软件的使用
  14. sqlmap注入之tamper绕过WAF防火墙过滤
  15. 17年社交网络老司机解读网红现象
  16. 群晖DSM Docker下Xware迅雷远程下载教程
  17. PS网页设计教程XXI——在Photoshop中创建一个光质感网页设计
  18. 服务器硬件规格常用查看命令——CPU相关命令
  19. GroovyGrails
  20. 把一个字符串中的大写字母和小写字母分别存储到一个新的字符串中

热门文章

  1. python画结构图_【实战案例】五分钟!用python绘制系统架构图
  2. php 改变键值,php数组中子数组如何修改键值
  3. java-nio网络编程
  4. Justinmind使用教程(6)——Justinmind的切换事件toggle
  5. 番外7林芝·救赎之旅的最后一站——混合现实科幻《地与光》
  6. [200814] 自己动手,搞定软件著作权申请(已成功)
  7. win10备份(win10备份的系统怎么还原)
  8. html编写扑克牌游戏,用js编写扑克牌小游戏
  9. Heapsort 代码 学习笔记 阳春三月版
  10. html如何设置本地链接,本地连接受限制或无连接【方法|图文教程】-太平洋IT百科...