亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

項目地址:

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: 排序規(guī)則,可選: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爬取新聞門戶網(wǎng)站的示例的詳細內(nèi)容,更多關于python爬取新聞門戶網(wǎng)站的資料請關注腳本之家其它相關文章!

相關文章

  • Python字典一個key對應多個value幾種實現(xiàn)方式

    Python字典一個key對應多個value幾種實現(xiàn)方式

    python中字典的健和值是一一對應的,如果對字典進行添加操作時如果健的名字相同,則當前健對應的值就會被覆蓋,有時候我們想要一個健對應多個值的場景,這篇文章主要給大家介紹了關于Python字典一個key對應多個value幾種實現(xiàn)方式的相關資料,需要的朋友可以參考下
    2023-10-10
  • python列表生成器迭代器實例解析

    python列表生成器迭代器實例解析

    這篇文章主要介紹了python列表生成器迭代器實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • Python基礎語法之變量與數(shù)據(jù)類型詳解

    Python基礎語法之變量與數(shù)據(jù)類型詳解

    這篇文章主要為大家詳細介紹了Python基礎語法中變量與數(shù)據(jù)類型的用法,文中的示例代碼講解詳細,對我們學習Python有一定的幫助,感興趣的可以了解一下
    2022-07-07
  • Python中tkinter的用戶登錄管理的實現(xiàn)

    Python中tkinter的用戶登錄管理的實現(xiàn)

    這篇文章主要介紹了Python中tkinter的用戶登錄管理的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • python利用rsa庫做公鑰解密的方法教程

    python利用rsa庫做公鑰解密的方法教程

    RSA是一種公鑰密碼算法,RSA的密文是對代碼明文的數(shù)字的 E 次方求mod N 的結(jié)果。下面這篇文章主要給大家介紹了關于python利用rsa庫做公鑰解密的方法教程,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。
    2017-12-12
  • python如何實現(xiàn)int函數(shù)的方法示例

    python如何實現(xiàn)int函數(shù)的方法示例

    int()函數(shù)常用來把其他類型轉(zhuǎn)換為整數(shù),下面這篇文章主要給大家介紹了關于python如何實現(xiàn)int函數(shù)的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。
    2018-02-02
  • python實現(xiàn)上傳樣本到virustotal并查詢掃描信息的方法

    python實現(xiàn)上傳樣本到virustotal并查詢掃描信息的方法

    這篇文章主要介紹了python實現(xiàn)上傳樣本到virustotal并查詢掃描信息的方法,是比較實用的技巧,需要的朋友可以參考下
    2014-10-10
  • Python 獲取當前所在目錄的方法詳解

    Python 獲取當前所在目錄的方法詳解

    本文給大家講解的是使用python獲取當前所在目錄的方法以及相關示例,非常的清晰簡單,有需要的小伙伴可以參考下
    2017-08-08
  • Python中的隨機函數(shù)random詳解

    Python中的隨機函數(shù)random詳解

    大家好,本篇文章主要講的是Python中的隨機函數(shù)random詳解,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • python訪問類中docstring注釋的實現(xiàn)方法

    python訪問類中docstring注釋的實現(xiàn)方法

    這篇文章主要介紹了python訪問類中docstring注釋的實現(xiàn)方法,涉及python類注釋的訪問技巧,非常具有實用價值,需要的朋友可以參考下
    2015-05-05

最新評論