python爬取新聞門(mén)戶網(wǎng)站的示例
項(xiàng)目地址:
https://github.com/Python3Spiders/AllNewsSpider
如何使用
每個(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('.//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()
# ./ 是直接下級(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')
以上就是python爬取新聞門(mén)戶網(wǎng)站的示例的詳細(xì)內(nèi)容,更多關(guān)于python爬取新聞門(mén)戶網(wǎng)站的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- python 爬取壁紙網(wǎng)站的示例
- Python爬取網(wǎng)站圖片并保存的實(shí)現(xiàn)示例
- Python爬蟲(chóng)設(shè)置Cookie解決網(wǎng)站攔截并爬取螞蟻短租的問(wèn)題
- python 多線程爬取壁紙網(wǎng)站的示例
- python爬蟲(chóng)爬取某網(wǎng)站視頻的示例代碼
- python爬蟲(chóng)實(shí)現(xiàn)爬取同一個(gè)網(wǎng)站的多頁(yè)數(shù)據(jù)的實(shí)例講解
- sql coalesce函數(shù)的具體使用
- python 爬取免費(fèi)簡(jiǎn)歷模板網(wǎng)站的示例
- Python3 實(shí)現(xiàn)爬取網(wǎng)站下所有URL方式
- 使用python爬取taptap網(wǎng)站游戲截圖的步驟
相關(guān)文章
Python字典一個(gè)key對(duì)應(yīng)多個(gè)value幾種實(shí)現(xiàn)方式
python中字典的健和值是一一對(duì)應(yīng)的,如果對(duì)字典進(jìn)行添加操作時(shí)如果健的名字相同,則當(dāng)前健對(duì)應(yīng)的值就會(huì)被覆蓋,有時(shí)候我們想要一個(gè)健對(duì)應(yīng)多個(gè)值的場(chǎng)景,這篇文章主要給大家介紹了關(guān)于Python字典一個(gè)key對(duì)應(yīng)多個(gè)value幾種實(shí)現(xiàn)方式的相關(guān)資料,需要的朋友可以參考下2023-10-10
Python基礎(chǔ)語(yǔ)法之變量與數(shù)據(jù)類(lèi)型詳解
這篇文章主要為大家詳細(xì)介紹了Python基礎(chǔ)語(yǔ)法中變量與數(shù)據(jù)類(lèi)型的用法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的可以了解一下2022-07-07
Python中tkinter的用戶登錄管理的實(shí)現(xiàn)
這篇文章主要介紹了Python中tkinter的用戶登錄管理的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
python如何實(shí)現(xiàn)int函數(shù)的方法示例
int()函數(shù)常用來(lái)把其他類(lèi)型轉(zhuǎn)換為整數(shù),下面這篇文章主要給大家介紹了關(guān)于python如何實(shí)現(xiàn)int函數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02
python實(shí)現(xiàn)上傳樣本到virustotal并查詢掃描信息的方法
這篇文章主要介紹了python實(shí)現(xiàn)上傳樣本到virustotal并查詢掃描信息的方法,是比較實(shí)用的技巧,需要的朋友可以參考下2014-10-10
python訪問(wèn)類(lèi)中docstring注釋的實(shí)現(xiàn)方法
這篇文章主要介紹了python訪問(wèn)類(lèi)中docstring注釋的實(shí)現(xiàn)方法,涉及python類(lèi)注釋的訪問(wèn)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-05-05

