作業要求來自:
1.從新聞url獲取新聞詳情: 字典,anews
3.生成所頁列表頁的url並獲取全部新聞 :列表extend(列表) allnews
*每個同學爬學號尾數開始的10個列表頁
4.設定合理的爬取間隔
源**如下:
import執行結果如下圖所示:requests
import
refrom bs4 import
beautifulsoup
from datetime import
datetime
import
pandas as pd
import
time
import
random
#從新聞url獲取新聞詳情: 字典,anews
def click(url):#
獲取點選次數
id=re.findall('
(\d)
',url)[-1]
clickurl='
'.format(id)
res=requests.get(clickurl)
newsclick=res.text.split('
.html
')[-1].lstrip("
('").rstrip("
');"
)
return
newsclick
def newsdt(showinfo):#
轉換成datetime型別
newsdate=showinfo.split()[0].split('
:')[1]
newstime=showinfo.split()[1]
newsdt=newsdate+'
'+newstime
dt=datetime.strptime(newsdt,'
%y-%m-%d %h:%m:%s')
return
dtdef new(url):#
獲取校園的點選次數,時間,標題
newsdetail={}
res=requests.get(url)
res.encoding='
utf-8
'soup=beautifulsoup(res.text,'
html.parser')
newsdetail[
'nenewstitle
']=soup.select('
.show-title
')[0].text
showinfo=soup.select('
.show-info
')[0].text
newsdetail[
'newsdt
']=newsdt(showinfo)
newsdetail[
'newsclick
']=click(url)
#newsdetail['newdesc']=soup.select('.news-list-description')[0].text
return
newsdetail
#listurl=''
#print(soup)
res=requests.get(listurl)
res.encoding='
utf-8
'soup = beautifulsoup(res.text,'
html.parser')
newslist =
for news in soup.select('li'
):
if len(news.select('
.news-list-title
'))>0:
newsurl=news.select('
a')[0]['
href
']#獲取鏈結
#print(newsurl)
newsdesc=news.select('
.news-list-description
')[0].text
newsdict=new(newsurl)
newsdict[
'description
']=newsdesc
return
newslist
#print(newslist)
#alist(listurl)
i=int(soup.select('
#pages
')[0].text.split('
..')[1].rstrip('
'))#
獲取校園新聞的頁數,去除多餘的東西
allnews=
for i in range(96,106):#
獲取96~106頁數的校園新聞的各項資訊,生成所頁列表頁的url並獲取全部新聞 :列表extend(列表) allnews
listurl='
{}.html
'.format(i)
allnews.extend(alist(listurl))
for i in range(5):#
設定合理的爬取間隔
time.sleep(random.random()*3)
newsdf = pd.dataframe(allnews)#
轉化為二維的**型資料結構
newsdf
5.用pandas做簡單的資料處理並儲存
儲存到csv或excel檔案
import執行結果:sqlite3
newsdf.to_csv(r
'f:\gzccnews.csv
')
成功儲存到了f盤中的gzccnews5.csv中
儲存到資料庫
import執行結果:sqlite3
with sqlite3.connect(
'gzccnewsdb5.sqlite
') as db:
newsdf.to_sql(
'gzccnewsdb5
',db)
with sqlite3.connect(
'gzccnewsdb5.sqlite
') as db:
df2=pd.read_sql_query('
select * from gzccnewsdb5
',con=db)
df2[df2[
'newsclick
']>300]
爬取全部的校園新聞
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...