您好,登錄后才能下訂單哦!
這篇文章主要介紹了python如何爬取新聞門(mén)戶網(wǎng)站,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
1、云計(jì)算,典型應(yīng)用OpenStack。2、WEB前端開(kāi)發(fā),眾多大型網(wǎng)站均為Python開(kāi)發(fā)。3.人工智能應(yīng)用,基于大數(shù)據(jù)分析和深度學(xué)習(xí)而發(fā)展出來(lái)的人工智能本質(zhì)上已經(jīng)無(wú)法離開(kāi)python。4、系統(tǒng)運(yùn)維工程項(xiàng)目,自動(dòng)化運(yùn)維的標(biāo)配就是python+Django/flask。5、金融理財(cái)分析,量化交易,金融分析。6、大數(shù)據(jù)分析。
每個(gè)文件夾下的代碼就是對(duì)應(yīng)平臺(tái)的新聞爬蟲(chóng)
py 文件直接運(yùn)行
pyd 文件需要,假設(shè)為 pengpai_news_spider.pyd
將 pyd 文件下載到本地,新建項(xiàng)目,把 pyd 文件放進(jìn)去
項(xiàng)目根目錄下新建 runner.py,寫(xiě)入以下代碼即可運(yùn)行并抓取
import pengpai_news_spider pengpai_news_spider.main()
百度新聞
# -*- coding: utf-8 -*- # 文件備注信息 如果遇到打不開(kāi)的情況,可以先在瀏覽器打開(kāi)一下百度搜索引擎 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 '小時(shí)' in unformatedTime: hour = unformatedTime[:unformatedTime.find('小時(shí)')] 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('.//h4/a')[0] title = title.xpath('string(.)').strip() summary = result.xpath('.//span[@class="c-font-normal c-color-text"]')[0] summary = summary.xpath('string(.)').strip() # ./ 是直接下級(jí),.// 是直接/間接下級(jí) 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('來(lái)源', source) print('時(shí)間', 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 按時(shí)間排序 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(按時(shí)間排序),默認(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('第 {} 頁(yè)\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 = '馬保國(guó)', sortBy='focus')
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“python如何爬取新聞門(mén)戶網(wǎng)站”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。