最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python爬取新聞門戶網(wǎng)站的示例

 更新時間:2021年04月25日 16:31:08   作者:Python3Spiders  
短期目前旨在爬取所有新聞門戶網(wǎng)站的新聞,每個門戶網(wǎng)站爬蟲開箱即用,并自動保存到同目錄下的 csv/excel 文件中,禁止將所得數(shù)據(jù)商用。

項(xiàng)目地址:

https://github.com/Python3Spiders/AllNewsSpider

如何使用

每個文件夾下的代碼就是對應(yīng)平臺的新聞爬蟲

  1. py 文件直接運(yùn)行
  2. pyd 文件需要,假設(shè)為 pengpai_news_spider.pyd

將 pyd 文件下載到本地,新建項(xiàng)目,把 pyd 文件放進(jìn)去

項(xiàng)目根目錄下新建 runner.py,寫入以下代碼即可運(yùn)行并抓取

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('標(biāo)題', 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 按焦點(diǎn)排序
    '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: 搜索關(guān)鍵詞
    :param sortBy: 排序規(guī)則,可選:focus(按焦點(diǎn)排序),time(按時間排序),默認(rèn) 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爬取新聞門戶網(wǎng)站的示例的詳細(xì)內(nèi)容,更多關(guān)于python爬取新聞門戶網(wǎng)站的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python中__init__.py文件的作用

    Python中__init__.py文件的作用

    這篇文章主要介紹了Python中__init__.py文件的作用,在PyCharm中,帶有__init__.py這個文件的目錄被認(rèn)為是Python的包目錄,與普通目錄的圖標(biāo)有不一樣的顯示
    2022-09-09
  • Pytorch: 自定義網(wǎng)絡(luò)層實(shí)例

    Pytorch: 自定義網(wǎng)絡(luò)層實(shí)例

    今天小編就為大家分享一篇Pytorch: 自定義網(wǎng)絡(luò)層實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python3中確保枚舉值代碼分析

    python3中確保枚舉值代碼分析

    在本篇文章里小編給大家整理的是一篇關(guān)于python3中確保枚舉值代碼分析內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2020-12-12
  • Python實(shí)現(xiàn)合并與拆分多個PDF文檔中的指定頁

    Python實(shí)現(xiàn)合并與拆分多個PDF文檔中的指定頁

    這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)將多個PDF文檔中的指定頁合并生成新的PDF以及拆分PDF,感興趣的小伙伴可以參考一下
    2025-03-03
  • python原始套接字編程示例分享

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

    在實(shí)驗(yàn)中需要自己構(gòu)造單獨(dú)的HTTP數(shù)據(jù)報文,而使用SOCK_STREAM進(jìn)行發(fā)送數(shù)據(jù)包,需要進(jìn)行完整的TCP交互。因此想使用原始套接字進(jìn)行編程,直接構(gòu)造數(shù)據(jù)包,并在IP層進(jìn)行發(fā)送,即采用SOCK_RAW進(jìn)行數(shù)據(jù)發(fā)送。使用SOCK_RAW的優(yōu)勢是,可以對數(shù)據(jù)包進(jìn)行完整的修改,可以處理IP層上的所有數(shù)據(jù)包,對各字段進(jìn)行修改,而不受UDP和TCP的限制。
    2014-02-02
  • PyTorch CNN實(shí)戰(zhàn)之MNIST手寫數(shù)字識別示例

    PyTorch CNN實(shí)戰(zhàn)之MNIST手寫數(shù)字識別示例

    本篇文章主要介紹了PyTorch CNN實(shí)戰(zhàn)之MNIST手寫數(shù)字識別示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • pandas 空的dataframe 插入列名的示例

    pandas 空的dataframe 插入列名的示例

    今天小編就為大家分享一篇pandas 空的dataframe 插入列名的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python學(xué)習(xí)之Anaconda的使用與配置方法

    Python學(xué)習(xí)之Anaconda的使用與配置方法

    我在學(xué)習(xí)Python的爬蟲框架中看到看到了anaconda的介紹,簡直是相見恨晚啊,我覺的每個Python的學(xué)習(xí)網(wǎng)站上首先都應(yīng)該使用anaconda來進(jìn)行教程,因?yàn)樵趯?shí)踐的過程中光環(huán)境的各種報錯就能消磨掉你所有的學(xué)習(xí)興趣
    2018-01-01
  • Python之多線程退出與停止的一種實(shí)現(xiàn)思路

    Python之多線程退出與停止的一種實(shí)現(xiàn)思路

    這篇文章主要介紹了Python之多線程退出與停止的一種實(shí)現(xiàn)思路,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • 深入了解如何基于Python讀寫Kafka

    深入了解如何基于Python讀寫Kafka

    這篇文章主要介紹了深入了解如何基于Python讀寫Kafka,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12

最新評論

个旧市| 曲阜市| 阳谷县| 汤原县| 南召县| 仙桃市| 随州市| 青岛市| 禹州市| 庐江县| 宕昌县| 阜宁县| 西平县| 合江县| 克什克腾旗| 丰台区| 鄂州市| 西充县| 牟定县| 双辽市| 托克托县| 永兴县| 沈丘县| 自治县| 囊谦县| 拜泉县| 新宁县| 庆云县| 潮州市| 雷波县| 铅山县| 孟津县| 永定县| 南平市| 万年县| 郁南县| 进贤县| 乌审旗| 清水县| 云南省| 尤溪县|