一、介绍

    本例子用Selenium +phantomjs爬取今日头条(http://www.toutiao.com/search/?keyword=电视)的资讯信息,输入给定关键字抓取资讯信息。

    给定关键字:数字;融合;电视

    抓取信息内如下:

      1、资讯标题

      2、资讯链接

      3、资讯时间

      4、资讯来源

 

  二、网站信息

    

    

    

 

  三、数据抓取

    针对上面的网站信息,来进行抓取

    1、首先抓取信息列表

      抓取代码:Elements = doc('div[class="articleCard"]')

    2、抓取标题

      抓取代码:title = element('a[class="link title"]').find('span').text().encode('utf8').replace(' ', '')

    3、抓取链接

      抓取代码:url = 'http://www.toutiao.com' + element.find('a[class="link title"]').attr('href')

    4、抓取日期

      抓取代码:strdate = element('span[class="lbtn"]').text().encode('utf8').strip()

    5、抓取来源

      抓取代码:source = element('a[class="lbtn source J_source"]').text().encode('utf8').replace(' ', '')

  

  四、完整代码

  1. # coding=utf-8
  2. import os
  3. import re
  4. from selenium import webdriver
  5. import selenium.webdriver.support.ui as ui
  6. import time
  7. from datetime import datetime
  8. import IniFile
  9. # from threading import Thread
  10. from pyquery import PyQuery as pq
  11. import LogFile
  12. import mongoDB
  13. import urllib
  14. class toutiaoSpider(object):
  15. def __init__(self):
  16.  
  17. logfile = os.path.join(os.path.dirname(os.getcwd()), time.strftime('%Y-%m-%d') + '.txt')
  18. self.log = LogFile.LogFile(logfile)
  19. configfile = os.path.join(os.path.dirname(os.getcwd()), 'setting.conf')
  20. cf = IniFile.ConfigFile(configfile)
  21. webSearchUrl = cf.GetValue("toutiao", "webSearchUrl")
  22. self.keyword_list = cf.GetValue("section", "information_keywords").split(';')
  23. self.db = mongoDB.mongoDbBase()
  24. self.start_urls = []
  25.  
  26. for word in self.keyword_list:
  27. self.start_urls.append(webSearchUrl + urllib.quote(word))
  28.  
  29. self.driver = webdriver.PhantomJS()
  30. self.wait = ui.WebDriverWait(self.driver, 2)
  31. self.driver.maximize_window()
  32.  
  33. def scroll_foot(self):
  34. '''
  35. 滚动条拉到底部
  36. :return:
  37. '''
  38. js = ""
  39. # 如何利用chrome驱动或phantomjs抓取
  40. if self.driver.name == "chrome" or self.driver.name == 'phantomjs':
  41. js = "var q=document.body.scrollTop=10000"
  42. # 如何利用IE驱动抓取
  43. elif self.driver.name == 'internet explorer':
  44. js = "var q=document.documentElement.scrollTop=10000"
  45. return self.driver.execute_script(js)
  46.  
  47. def date_isValid(self, strDateText):
  48. '''
  49. 判断日期时间字符串是否合法:如果给定时间大于当前时间是合法,或者说当前时间给定的范围内
  50. :param strDateText: 四种格式 '2小时前'; '2天前' ; '昨天' ;'2017.2.12 '
  51. :return: True:合法;False:不合法
  52. '''
  53. currentDate = time.strftime('%Y-%m-%d')
  54. if strDateText.find('分钟前') > 0 or strDateText.find('刚刚') > -1:
  55. return True, currentDate
  56. elif strDateText.find('小时前') > 0:
  57. datePattern = re.compile(r'\d{1,2}')
  58. ch = int(time.strftime('%H')) # 当前小时数
  59. strDate = re.findall(datePattern, strDateText)
  60. if len(strDate) == 1:
  61. if int(strDate[0]) <= ch: # 只有小于当前小时数,才认为是今天
  62. return True, currentDate
  63. return False, ''
  64.  
  65. def log_print(self, msg):
  66. '''
  67. # 日志函数
  68. # :param msg: 日志信息
  69. # :return:
  70. # '''
  71. print '%s: %s' % (time.strftime('%Y-%m-%d %H-%M-%S'), msg)
  72.  
  73. def scrapy_date(self):
  74. strsplit = '------------------------------------------------------------------------------------'
  75. index = 0
  76. for link in self.start_urls:
  77. self.driver.get(link)
  78.  
  79. keyword = self.keyword_list[index]
  80. index = index + 1
  81. time.sleep(1) #数据比较多,延迟下,否则会出现查不到数据的情况
  82.  
  83. selenium_html = self.driver.execute_script("return document.documentElement.outerHTML")
  84. doc = pq(selenium_html)
  85. infoList = []
  86. self.log.WriteLog(strsplit)
  87. self.log_print(strsplit)
  88.  
  89. Elements = doc('div[class="articleCard"]')
  90.  
  91. for element in Elements.items():
  92. strdate = element('span[class="lbtn"]').text().encode('utf8').strip()
  93. flag, date = self.date_isValid(strdate)
  94. if flag:
  95. title = element('a[class="link title"]').find('span').text().encode('utf8').replace(' ', '')
  96. if title.find(keyword) > -1:
  97. url = 'http://www.toutiao.com' + element.find('a[class="link title"]').attr('href')
  98. source = element('a[class="lbtn source J_source"]').text().encode('utf8').replace(' ', '')
  99.  
  100. dictM = {'title': title, 'date': date,
  101. 'url': url, 'keyword': keyword, 'introduction': title, 'source': source}
  102. infoList.append(dictM)
  103. # self.log.WriteLog('title:%s' % title)
  104. # self.log.WriteLog('url:%s' % url)
  105. # self.log.WriteLog('source:%s' % source)
  106. # self.log.WriteLog('kword:%s' % keyword)
  107. # self.log.WriteLog(strsplit)
  108.  
  109. self.log_print('title:%s' % dictM['title'])
  110. self.log_print('url:%s' % dictM['url'])
  111. self.log_print('date:%s' % dictM['date'])
  112. self.log_print('source:%s' % dictM['source'])
  113. self.log_print('kword:%s' % dictM['keyword'])
  114. self.log_print(strsplit)
  115.  
  116. if len(infoList)>0:
  117. self.db.SaveInformations(infoList)
  118.  
  119. self.driver.close()
  120. self.driver.quit()
  121.  
  122. obj = toutiaoSpider()
  123. obj.scrapy_date()

[Python爬虫] 之二十五:Selenium +phantomjs 利用 pyquery抓取今日头条网数据的更多相关文章

  1. [Python爬虫] 之二十七:Selenium +phantomjs 利用 pyquery抓取今日头条视频

    一.介绍 本例子用Selenium +phantomjs爬取今天头条视频(http://www.tvhome.com/news/)的信息,输入给定关键字抓取图片信息. 给定关键字:视频:融合:电视 二 ...

  2. [Python爬虫] 之二十一:Selenium +phantomjs 利用 pyquery抓取36氪网站数据

    一.介绍 本例子用Selenium +phantomjs爬取36氪网站(http://36kr.com/search/articles/电视?page=1)的资讯信息,输入给定关键字抓取资讯信息. 给 ...

  3. [Python爬虫] 之二十三:Selenium +phantomjs 利用 pyquery抓取智能电视网数据

    一.介绍 本例子用Selenium +phantomjs爬取智能电视网(http://news.znds.com/article/news/)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字 ...

  4. [Python爬虫] 之二十:Selenium +phantomjs 利用 pyquery通过搜狗搜索引擎数据

    一.介绍 本例子用Selenium +phantomjs 利用 pyquery通过搜狗搜索引擎数据()的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字:融合:电视 抓取信息内如下: 1.资讯 ...

  5. [Python爬虫] 之十九:Selenium +phantomjs 利用 pyquery抓取超级TV网数据

    一.介绍 本例子用Selenium +phantomjs爬取超级TV(http://www.chaojitv.com/news/index.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键 ...

  6. [Python爬虫] 之二十四:Selenium +phantomjs 利用 pyquery抓取中广互联网数据

    一.介绍 本例子用Selenium +phantomjs爬取中广互联网(http://www.tvoao.com/select.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字:融 ...

  7. [Python爬虫] 之三十:Selenium +phantomjs 利用 pyquery抓取栏目

    一.介绍 本例子用Selenium +phantomjs爬取栏目(http://tv.cctv.com/lm/)的信息 二.网站信息 三.数据抓取 首先抓取所有要抓取网页链接,共39页,保存到数据库里 ...

  8. [Python爬虫] 之二十八:Selenium +phantomjs 利用 pyquery抓取网站排名信息

    一.介绍 本例子用Selenium +phantomjs爬取中文网站总排名(http://top.chinaz.com/all/index.html,http://top.chinaz.com/han ...

  9. [Python爬虫] 之二十九:Selenium +phantomjs 利用 pyquery抓取节目信息信息

    一.介绍 本例子用Selenium +phantomjs爬取节目(http://tv.cctv.com/epg/index.shtml?date=2018-03-25)的信息 二.网站信息 三.数据抓 ...

随机推荐

  1. HDU1028 (整数拆分)

    Ignatius and the Princess III Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K ...

  2. 智联招聘的python岗位数据词云制作

    # 根据传入的背景图片路径和词频字典.字体文件,生成指定名称的词云图片 def generate_word_cloud(img_bg_path, top_words_with_freq, font_p ...

  3. javascript中使用el表达式获取不到数据问题

    我们通常会在jsp里面使用el表达式,把需要的值传递给 javascript 方法,例如: <p onclick="doSomething(${param})">< ...

  4. Selenium2+python自动化74-jquery定位【转载】

    转至博客:上海-悠悠 前言 元素定位可以说是学自动化的小伙伴遇到的一道门槛,学会了定位也就打通了任督二脉,前面分享过selenium的18般武艺,再加上五种js的定位大法. 这些还不够的话,今天再分享 ...

  5. 关系和非关系型数据库区别(以及oracle和mysql的区别)

    一.关系型数据库 关系型数据库,是指采用了关系模型来组织数据的数据库.    关系模型是在1970年由IBM的研究员E.F.Codd博士首先提出的,在之后的几十年中,关系模型的概念得到了充分的发展并逐 ...

  6. 更改yum源为网易的

    更改yum源为网易的. mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup cd /etc/yu ...

  7. maven编译生成的jar包运行出现 "Failed to load Main-Class manifest attribute from"

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  8. [BZOJ3027][Ceoi2004]Sweet 容斥+组合数

    3027: [Ceoi2004]Sweet Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 135  Solved: 66[Submit][Status] ...

  9. jmeter 线程组之间的参数传递

    http://www.cnblogs.com/wnfindbug/p/5817277.html 场景测试中,一次登录后做多个接口的操作,然后登录后的uid需要关联传递给其他接口发送请求的时候使用. 1 ...

  10. Eclipse 教程 | 菜鸟教程

    http://www.runoob.com/eclipse/eclipse-charset.html