python爬取新闻门户网站的示例

 更新时间:2021年04月25日 16:31:08   作者:Python3Spiders  
短期目前旨在爬取所有新闻门户网站的新闻,每个门户网站爬虫开箱即用,并自动保存到同目录下的 csv/excel 文件中,禁止将所得数据商用。

项目地址:

https://github.com/Python3Spiders/AllNewsSpider

如何使用

每个文件夹下的代码就是对应平台的新闻爬虫

  1. py 文件直接运行
  2. pyd 文件需要,假设为 pengpai_news_spider.pyd

将 pyd 文件下载到本地,新建项目,把 pyd 文件放进去

项目根目录下新建 runner.py,写入以下代码即可运行并抓取

import pengpai_news_spider
pengpai_news_spider.main()

示例代码

百度新闻

# -*- coding: utf-8 -*-
# 文件备注信息       如果遇到打不开的情况,可以先在浏览器打开一下百度搜索引擎

import requests

from datetime import datetime, timedelta

from lxml import etree

import csv

import os

from time import sleep
from random import randint


def parseTime(unformatedTime):
    if '分钟' in unformatedTime:
        minute = unformatedTime[:unformatedTime.find('分钟')]
        minute = timedelta(minutes=int(minute))
        return (datetime.now() -
                minute).strftime('%Y-%m-%d %H:%M')
    elif '小时' in unformatedTime:
        hour = unformatedTime[:unformatedTime.find('小时')]
        hour = timedelta(hours=int(hour))
        return (datetime.now() -
                hour).strftime('%Y-%m-%d %H:%M')
    else:
        return unformatedTime


def dealHtml(html):
    results = html.xpath('//div[@class="result-op c-container xpath-log new-pmd"]')

    saveData = []

    for result in results:
        title = result.xpath('.//h3/a')[0]
        title = title.xpath('string(.)').strip()

        summary = result.xpath('.//span[@class="c-font-normal c-color-text"]')[0]
        summary = summary.xpath('string(.)').strip()

        # ./ 是直接下级,.// 是直接/间接下级
        infos = result.xpath('.//div[@class="news-source"]')[0]
        source, dateTime = infos.xpath(".//span[last()-1]/text()")[0], \
                           infos.xpath(".//span[last()]/text()")[0]

        dateTime = parseTime(dateTime)

        print('标题', title)
        print('来源', source)
        print('时间', dateTime)
        print('概要', summary)
        print('\n')

        saveData.append({
            'title': title,
            'source': source,
            'time': dateTime,
            'summary': summary
        })
    with open(fileName, 'a+', encoding='utf-8-sig', newline='') as f:
        writer = csv.writer(f)
        for row in saveData:
            writer.writerow([row['title'], row['source'], row['time'], row['summary']])


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
    'Referer': 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=%B0%D9%B6%C8%D0%C2%CE%C5&fr=zhidao'
}

url = 'https://www.baidu.com/s'

params = {
    'ie': 'utf-8',
    'medium': 0,
    # rtt=4 按时间排序 rtt=1 按焦点排序
    'rtt': 1,
    'bsst': 1,
    'rsv_dl': 'news_t_sk',
    'cl': 2,
    'tn': 'news',
    'rsv_bp': 1,
    'oq': '',
    'rsv_btype': 't',
    'f': 8,
}


def doSpider(keyword, sortBy = 'focus'):
    '''
    :param keyword: 搜索关键词
    :param sortBy: 排序规则,可选:focus(按焦点排序),time(按时间排序),默认 focus
    :return:
    '''
    global fileName
    fileName = '{}.csv'.format(keyword)

    if not os.path.exists(fileName):
        with open(fileName, 'w+', encoding='utf-8-sig', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['title', 'source', 'time', 'summary'])

    params['wd'] = keyword
    if sortBy == 'time':
        params['rtt'] = 4

    response = requests.get(url=url, params=params, headers=headers)

    html = etree.HTML(response.text)

    dealHtml(html)

    total = html.xpath('//div[@id="header_top_bar"]/span/text()')[0]

    total = total.replace(',', '')

    total = int(total[7:-1])

    pageNum = total // 10

    for page in range(1, pageNum):
        print('第 {} 页\n\n'.format(page))
        headers['Referer'] = response.url
        params['pn'] = page * 10

        response = requests.get(url=url, headers=headers, params=params)

        html = etree.HTML(response.text)

        dealHtml(html)

        sleep(randint(2, 4))
    ...


if __name__ == "__main__":
    doSpider(keyword = '马保国', sortBy='focus')

以上就是python爬取新闻门户网站的示例的详细内容,更多关于python爬取新闻门户网站的资料请关注脚本之家其它相关文章!

相关文章

  • Python中__init__.py文件的作用

    Python中__init__.py文件的作用

    这篇文章主要介绍了Python中__init__.py文件的作用,在PyCharm中,带有__init__.py这个文件的目录被认为是Python的包目录,与普通目录的图标有不一样的显示
    2022-09-09
  • Pytorch: 自定义网络层实例

    Pytorch: 自定义网络层实例

    今天小编就为大家分享一篇Pytorch: 自定义网络层实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python3中确保枚举值代码分析

    python3中确保枚举值代码分析

    在本篇文章里小编给大家整理的是一篇关于python3中确保枚举值代码分析内容,有兴趣的朋友们可以学习下。
    2020-12-12
  • Python实现合并与拆分多个PDF文档中的指定页

    Python实现合并与拆分多个PDF文档中的指定页

    这篇文章主要为大家详细介绍了如何使用Python实现将多个PDF文档中的指定页合并生成新的PDF以及拆分PDF,感兴趣的小伙伴可以参考一下
    2025-03-03
  • python原始套接字编程示例分享

    python原始套接字编程示例分享

    在实验中需要自己构造单独的HTTP数据报文,而使用SOCK_STREAM进行发送数据包,需要进行完整的TCP交互。因此想使用原始套接字进行编程,直接构造数据包,并在IP层进行发送,即采用SOCK_RAW进行数据发送。使用SOCK_RAW的优势是,可以对数据包进行完整的修改,可以处理IP层上的所有数据包,对各字段进行修改,而不受UDP和TCP的限制。
    2014-02-02
  • PyTorch CNN实战之MNIST手写数字识别示例

    PyTorch CNN实战之MNIST手写数字识别示例

    本篇文章主要介绍了PyTorch CNN实战之MNIST手写数字识别示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • pandas 空的dataframe 插入列名的示例

    pandas 空的dataframe 插入列名的示例

    今天小编就为大家分享一篇pandas 空的dataframe 插入列名的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python学习之Anaconda的使用与配置方法

    Python学习之Anaconda的使用与配置方法

    我在学习Python的爬虫框架中看到看到了anaconda的介绍,简直是相见恨晚啊,我觉的每个Python的学习网站上首先都应该使用anaconda来进行教程,因为在实践的过程中光环境的各种报错就能消磨掉你所有的学习兴趣
    2018-01-01
  • Python之多线程退出与停止的一种实现思路

    Python之多线程退出与停止的一种实现思路

    这篇文章主要介绍了Python之多线程退出与停止的一种实现思路,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • 深入了解如何基于Python读写Kafka

    深入了解如何基于Python读写Kafka

    这篇文章主要介绍了深入了解如何基于Python读写Kafka,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12

最新评论