美文网首页
Python 爬虫(爬取腾讯新闻)

Python 爬虫(爬取腾讯新闻)

作者: 哎呀我Qu | 来源:发表于2017-10-12 17:35 被阅读432次

趁热打铁,再来爬一下 TX 的网站 -- 科技 -腾讯网。腾讯新闻的科技板块,至于为什么爬这个板块?我们要做新时代的科技少年😂 😂 😂 。闲话少叙,快上车。

一、分析网页代码

打开网页并进入调试模式,可以看的我们要爬取的内容都在这个 <div> 中。

qqxw_01.png

打开看看,就是它们,这个网站默认加载 20 条新闻,拉到底部会加载更多。

qqxw_02.png

因为是爬取新闻,也不涉及翻页的问题(爬以前的旧文章干嘛?😢 )。与 36Kr 不同的是,36Kr 的新闻是按照时间顺序排列的,新的在前,而 TX 貌似是按照热度排列的,哪个点击量高哪个在前。也无所谓了,只要爬这前 20 个就行了,大约每 10 分钟会有 3 ~ 5 篇新文章。

我们在点开其中一个 <div> 看看要爬取的元素位置,如下图。

qqxw_03.png

跟 36Kr 差不多,藏了一层又一层,思路也是一样的,先拿到它们外层的那个没名的 <div>,再用 xpath 获取每个元素(因为 by_id、by_class_name 都行不通,我试过了😂 )。

二、爬虫代码

这里也不啰嗦了,直接贴。编写的思路跟前一篇爬 36Kr 的差不多,发现 xpath 这个东西很好用,感觉一般的网站都可以用 xpath 搞定。只是为了避免出现这样那样的错误,加了很多 try - except 来保证程序不崩😂 ,如果你有更好的方案,欢迎交流。

#!/usr/bin/env python
#coding:utf-8

from selenium import webdriver
import time
import requests

class News:
    def __init__(self):
        self.dr = webdriver.Chrome()
        self.dr.set_page_load_timeout(30)
        try:
            self.dr.get('https://xw.qq.com/m/tech/index.htm/')
        except Exception as e:
            print 'initDriverError: ', e
        else:
            pass

    def loadData(self):
        try:
            main_view = self.dr.find_element_by_id('__next')
            item_list = main_view.find_element_by_xpath("//div/div[@class='wrapper_channel']/div/div[3]")
        except Exception as e:
            print 'loadDataError: ', e
        else:
            i = 1
            while  i <= 20:
                try:
                    xpath_head = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']/div/div[@class='title']"
                    xpath_href = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']"
                    xpath_img  = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']/div/div[@class='image']/div[@class='image-inner']/img"

                    title = item_list.find_element_by_xpath(xpath_head).text
                    url   = item_list.find_element_by_xpath(xpath_href).get_attribute('href')
                    src   = item_list.find_element_by_xpath(xpath_img).get_attribute('src')

                except Exception as e:
                    # 同 36Kr 不太一样,腾讯新闻爬到这里有时就会出现异常,获取不到元素
                    # 所以,在这里向下滚动浏览器, try - except,重新获取元素
                    self.dr.execute_script('window.scrollBy(0,300)')
                    time.sleep(3)
                    try:
                        title = item_list.find_element_by_xpath(xpath_head).text
                        url   = item_list.find_element_by_xpath(xpath_href).get_attribute('href')
                        src   = item_list.find_element_by_xpath(xpath_img).get_attribute('src')
                    except Exception as e:
                        # 如果依旧获取不到,那么可能是视频格式的新闻,各元素的 xpath 不同
                        self.loadVideoData(item_list, i)
                    else:
                        self.saveData(title, url, src)

                else:
                    self.saveData(title, url, src)

                i += 1

        self.quit()

    def loadVideoData(self, item_list, i):
        try:
            # 视频格式的新闻,xpath 不同
            xpath_head = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']/div[@class='title']"
            xpath_href  = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']"
            xpath_img   = "//div[" + str(i) + "]/div[@class='wrap']/div[@class='inner ']/a[@class='link cf']/div[@class='image']/div[@class='image-inner']/img"

            title = item_list.find_element_by_xpath(xpath_head).text
            url   = item_list.find_element_by_xpath(xpath_href).get_attribute('href')
            src   = item_list.find_element_by_xpath(xpath_img).get_attribute('src')

        except Exception as e:
            print 'loadVideoDataError: ', e
        else:
            self.saveData(title, url, src)

    # 例如你要将数据爬下来,存入自己的服务器
    def saveData(self, title, url, src):
        form_data = {'title':title,'url':url,'src':src}
        headers = {}
        req_url = ''

        try:
            req = requests.post(req_url, headers = headers, data = form_data,)
        except Exception as e:
            print 'saveDataError: ', e
        else:
            if req.status_code == 201:
                print 'Save data successful'
            else:
                print 'Failed: ', req.status_code
                print req.text

    def quit(self):
        self.dr.quit()

i = 1
while i:
    News().loadData()
    print u'第 %d 次获取数据完毕' % i
    i += 1
    time.sleep(600)

10.1 假期到现在已经跑了 10 多天了,可以正常爬取数据,这里就不录效果展示 gif 了。只是有一个问题还存有疑问,获取网页元素时,如果先遍历拿到 <a class='link cf'> 标签,再通过 xpath 获取每个 <a> 标签里的标题、图片等数据,这时拿到的都是同一个数据。这个情况爬 36Kr 的时候也出现过,还请研究过的朋友指点一下。

欧了,大功告成,不明白的童鞋,可以看看前几篇文章,比较简单的是 “不得姐” 和 “糗百”,爬 36Kr 时遇到了点问题,编写的步骤和心路历程在上一篇写过了。

另外应该是简书的一个 bug,编写文章时,用 ``` 符号设置代码区域,如果粘贴大量代码,在下方继续编辑,点一下浏览器就闪退了。不知道你们有这种情况没有……

  • 如果看了我的文章对你有些帮助的话,点个❤️ 再走呗,我想弄个微博认证,需要 2000 个喜欢,还差 1900 多个😂 。

相关文章

网友评论

      本文标题:Python 爬虫(爬取腾讯新闻)

      本文链接:https://www.haomeiwen.com/subject/wycoyxtx.html