爬取全部的校園新聞

2022-05-16 20:59:56 字數 2454 閱讀 9886

0.從新聞url獲取點選次數,並整理成函式

1.從新聞url獲取新聞詳情: 字典,anews

3.生成所頁列表頁的url並獲取全部新聞 :列表extend(列表) allnews

*每個同學爬學號尾數開始的10個列表頁

4.設定合理的爬取間隔

import time

import random

time.sleep(random.random()*3)

5.用pandas做簡單的資料處理並儲存

儲存到csv或excel檔案 

newsdf.to_csv(r'f:\duym\爬蟲\gzccnews.csv')

6.**示例

import re

from bs4 import beautifulsoup

from datetime import datetime

import requests

import pandas as pd

import time

import random

"""新聞點選次數"""

def newsclick(newsurl):

newsid = re.findall('(\d+)', newsurl)[-1]

clickurl = ''.format(newsid)

resclicks = requests.get(clickurl).text

resclick = int(re.search("hits'[)].html[(]'(\d*)'[)]", resclicks).groups(0)[0])

return resclick

"""新聞發布時間"""

def newsdatetime(showinfo):

newsdate = showinfo.split()[0].split(':')[1]

newstime = showinfo.split()[1]

newsdatetime = newsdate + ' ' + newstime

datetime = datetime.strptime(newsdatetime, '%y-%m-%d %h:%m:%s') #型別轉換

return datetime

"""新聞字典"""

def newsdicts(newsurl):

newstext = requests.get(newsurl)

newstext.encoding = 'utf-8'

newssoup = beautifulsoup(newstext.text, 'html.parser')

newsdict = {}

newsdict['newstitle'] = newssoup.select('.show-title')[0].text

showinfo = newssoup.select('.show-info')[0].text

newsdict['newsdatetime'] = newsdatetime(showinfo)

newsdict['newsclick'] = newsclick(newsurl)

return newsdict

"""新聞列表"""

def newslist(newsurl):

newstext = requests.get(newsurl)

newstext.encoding = 'utf-8'

newssoup = beautifulsoup(newstext.text, 'html.parser')

newslist =

for news in newssoup.select('li'):

if len(news.select('.news-list-title')) > 0:

url = news.select('a')[0]['href']

newsdesc = news.select('.news-list-description')[0].text

newsdict = newsdicts(url)

newsdict['newsurl'] = url

newsdict['description'] = newsdesc

return newslist

"""27-37頁新聞列表"""

def allnews():

allnews =

for i in range(34,44):

newsurl = ''.format(i)

allnews.extend(newslist(newsurl))

time.sleep(random.random() * 3) #爬取間隔

return allnews

newsdf = pd.dataframe(allnews())

newsdf.to_csv('gzccnews.csv') #儲存為csv檔案

爬取全部的校園新聞

1 從新聞url獲取新聞詳情 2 從列表頁的url獲取新聞url 3 生成所頁列表頁的url並獲取全部新聞 4 設定合理的爬取間隔 5 用pandas做簡單的資料處理並儲存成csv和sql檔案 import requests from bs4 import beautifulsoup from da...

爬取全部的校園新聞

本次作業 於 import包 import re import requests from bs4 import beautifulsoup from datetime import datetime import time import random import pandas as pd 0.從...

爬取全部的校園新聞

本次作業的要求來自於 0.從新聞url獲取點選次數,並整理成函式 1.熟練運用re.search match findall 2.從新聞url獲取新聞詳情 字典,anews import requests from bs4 import beautifulsoup from datetime imp...