孤荷淩寒自學python第七十五天開始寫Python的第一個爬蟲5
孤荷淩寒自學python第七十五天開始寫Python的第一個爬蟲5
(完整學習過程屏幕記錄視頻地址在文末)
今天在上一天的基礎上繼續完成對我的第一個代碼程序的書寫。
直接上代碼。詳細過程見文末屏幕錄像。
```
import requests
from bs4 import BeautifulSoup
import re
import datetime
import pymongo
import _mty
import _mf
import _mbs4
import _mmongo
import _mre
import _mdb
import _mword
intc=0
def msgbox(info,titletext=‘孤荷淩寒的DB模塊對話框QQ578652607‘,style=0,isShowErrMsg=False):
return _mty.msgboxGhlh(info,titletext,style,isShowErrMsg)
def myfirst(s,h):
c2=_mdb.conLocaldbGhlh(r‘C:\ProgramData\SQLITE3\slone.s3db‘)
lstNm=[‘id‘,‘title‘,‘newdate‘,‘source‘,‘content‘,‘adddate‘]
lstType=[‘int‘,‘string‘,‘date‘,‘str‘,‘memo‘,‘date‘]
lstLong=[0,255,0,255,0,0]
lstNull=[‘not null‘,‘not null‘,‘not null‘,‘null‘,‘not null‘,‘null‘]
lstPrimary=[True,False,False,False,False,False]
lstAuto=[True,False,False,False,False,False]
c3=_mdb.conLocaldbGhlh(r‘C:\ProgramData\SQLITE3\new163.accdb‘)
strt=‘news163‘
a=_mdb.newTablePlusGhlh(‘sqlite‘,c2,strt,lstNm,lstType,lstLong,lstNull,lstPrimary,lstAuto)
msgbox(str(a))
cursor=c2.cursor()
b=_mdb.newTablePlusGhlh(‘acc‘,c3,strt,lstNm,lstType,lstLong,lstNull,lstPrimary,lstAuto)
cursor3=c3.cursor()
cursor.execute(‘select * from ‘ + strt + ‘;‘)
data=cursor.fetchall()
for i in data:
msgbox(str(i))
cursor3.execute(‘select * from ‘ + strt + ‘;‘)
data=cursor3.fetchall()
for i in data:
msgbox(str(i))
#return True
#-------------------------
r=requests.get(s,headers=h)
#print(r.text) #r.text得到的是頁面源html代碼
_mf.writeAllTextToTxtFileGhlh(‘1.txt‘,r.text)
bs=BeautifulSoup(r.text,features="lxml") #第二個參數指明了解析器,得到的是一個beautifulsoup對象
s=bs.prettify()
_mf.writeAllTextToTxtFileGhlh(‘2.txt‘,str(s))
rs=bs.select(‘.bigsize‘) #選擇指定style樣式表的html標簽元素
for i in rs:
ele=i.find_all(‘a‘) #每個h5標簽下只有一個a標簽
strls=ele[0].get(‘href‘)
#msgbox(strls) #取出地址
getcontentpage(strls,h,c2,cursor,c3,cursor3,strt)
#break
#---------------------
#cursor.execute(‘select * from ‘ + strt + ‘;‘)
#data=cursor.fetchall()
#for i in data:
# msgbox(str(i))
#cursor3.execute(‘select * from ‘ + strt + ‘;‘)
#data=cursor3.fetchall()
#for i in data:
# msgbox(str(i))
def getcontentpage(strurl,h,c2,cursor,c3,cursor3,strt):
r=requests.get(strurl,headers=h)
_mf.writeAllTextToTxtFileGhlh(‘3.txt‘,r.text)
bs=BeautifulSoup(r.text,features="lxml") #第二個參數指明了解析器,得到的是一個beautifulsoup對象
s=bs.prettify()
_mf.writeAllTextToTxtFileGhlh(‘4.txt‘,str(s))
#---------------------------
#eletemp=bs.find_all("#epContentLeft") #現在eletemp是一個rs集合對象
#上一句是錯誤的,通過html標簽對象的id值來查找應當使用的方法是:select方法
eletemp=bs.select(‘#epContentLeft‘) #list
#msgbox(str(type(eletemp)))
eletitleparent=eletemp[0] #bs.element.Tag
#msgbox(str(type(eletitleparent)))
eletitle=eletitleparent.h1
elesource=eletitleparent.div #elesource這種對象現在被稱為:bs.element.Tag對象,可以被轉換為列表,但不是列表
#msgbox(str(elesource))
strtitle=_mbs4.getAllTextGhlh(eletitle)
strdate=list(elesource)[0]
strdate=_mre.getDateAndTimeString(strdate)
strsource=_mbs4.getAllTextGhlh(elesource.a)
#msgbox(strtitle)
#msgbox(strsource)
#msgbox(strdate)
#取正文
elecontent=bs.select(‘#endText‘) #所有的正文內容都這個div中,elecotent是一個List?
strcontent=_mbs4.getAllTextGhlh(elecontent)
data={
u‘標題‘:strtitle,
u‘日期‘:strdate,
u‘來源‘:strsource,
u‘內容‘:strcontent,
u‘添加日期‘:datetime.datetime.now().__format__(‘%Y-%m-%d %H:%M:%S‘)
}
#msgbox(str(data))
#寫入Mongodb數據庫
c=_mmongo.conMongoDbGhlh(‘localhost‘)
db=c.news163
jh=db.first
isok=_mmongo.addNewDataGhlh(jh,data)
#msgbox(isok)
#寫入sqlite3和ACCESS數據庫
try:
strsql="insert into " + strt + "(title,newdate,source,content,adddate) values(‘" + strtitle + "‘,‘" + strdate + "‘,‘" + strsource + "‘,‘" + strcontent + "‘,‘" + datetime.datetime.now().__format__(‘%Y-%m-%d %H:%M:%S‘) + "‘);"
cursor.execute(strsql)
cursor3.execute(strsql)
c2.commit()
c3.commit()
except:
msgbox(‘出錯了‘)
#寫入word文檔
try:
global intc
intc=intc+1
strf=‘%03d‘ %intc
strf=strf + ‘.docx‘
strf=‘I:\\MAKEAPP\\python\\Python365\\邊學習邊測試文件夾\\自學PYTHON部分\\0075第七十五天爬蟲實戰5\\‘ + strf
f=_mword.newDocX(strf)
f.add_heading(strtitle,level=2)
f.add_heading(strsource,level=3)
_mword.addPToDocx(f,strcontent)
f.save(strf) #保存時必須有文件名作參數
#f.close() #沒有這個命令
except:
msgbox(‘寫word出錯!‘)
pass
strurl=‘http://tech.163.com/special/techscience/‘
header={
‘Accept‘:‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8‘,
‘Accept-Encoding‘:‘gzip, deflate‘,
‘Accept-Language‘:‘zh-CN,zh;q=0.9‘,
‘Cache-Control‘:‘max-age=0‘,
‘Connection‘:‘keep-alive‘,
‘Cookie‘:‘_ntes_nuid=4c64ad6c80e3504f05302ac133efb277; _ntes_nnid=eb7c24e0daf48e922e31dc81e431fde2,1536978956105; Province=023; City=023; NNSSPID=acab5be191004a2b81a3a6ee60f516dc; NTES_hp_textlink1=old; UM_distinctid=1683adcaeaf2f8-0e31bcdad8532c-3c604504-144000-1683adcaeb094d; vjuids=-7a5afdb26.1683adccded.0.d9d34439a4e48; vjlast=1547175776.1547175776.30; ne_analysis_trace_id=1547175775731; s_n_f_l_n3=7476c45eb02177f91547175775852; vinfo_n_f_l_n3=7476c45eb02177f9.1.0.1547175775852.0.1547176062972‘,
‘Host‘:‘tech.163.com‘,
‘If-Modified-Since‘:‘Fri, 11 Jan 2019 03:01:05 GMT‘,
‘Referer‘:‘http://tech.163.com/‘,
‘Upgrade-Insecure-Requests‘:‘1‘,
‘User-Agent‘:‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36‘
}
header2={
‘Host‘:‘tech.163.com‘,
‘User-Agent‘:‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36‘
}
myfirst(strurl,header2)
```
二、今天為了將爬到的新聞放到word文檔中,寫了輔助的word模塊自定義的函數模塊
【_mword.py】
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
from docx import *
from docx.shared import Inches
import _mty
import _cl #常用常量模塊
import _mre
mwordErrString=‘‘
def msgbox(info,titletext=‘孤荷淩寒的word模塊對話框QQ578652607‘,style=0,isShowErrMsg=False):
return _mty.msgboxGhlh(info,titletext,style,isShowErrMsg)
def newDocX(strfilenm,isShowMsg=False):
‘‘‘
創建一個新的docx並保存在指定的路徑下成為指定文件名的文件 。
‘‘‘
try:
f=Document() #創建新文檔 對象
f.save(strfilenm) #保存這個文件
return f #f的類型是:<class ‘docx.document.Document‘>
except Exception as e:
mwordErrString=‘嘗試創建一個新的word文件時出錯:‘ + str(e) + ‘\n此函數由【孤荷淩寒】創建,QQ578652607‘
if isShowMsg==True:
msgbox(mwordErrString)
return None
else:
pass
finally:
pass
def addPToDocx(f,strp,isShowMsg=False):
try:
lst=strp.split(‘\n‘)
for i in lst:
i.strip()
p=f.add_paragraph(i)
#---接下來可調整格式
return True
except Exception as e:
mwordErrString=‘嘗試將來自網頁的內容寫入word文檔正文時出錯:‘ + str(e) + ‘\n此函數由【孤荷淩寒】創建,QQ578652607‘
if isShowMsg==True:
msgbox(mwordErrString)
return False
else:
pass
finally:
pass
#f=newDocX(r‘I:\MAKEAPP\python\Python365\邊學習邊測試文件夾\自學PYTHON部分\0075第七十五天爬蟲實戰5\孤荷淩寒.docx‘)
#print(type(f))
```
三、安裝word模塊與了解到的一些知識
(一)、安裝Python-docx
在windows的命令行窗口中輸入:
pip install python-docx
(二)、官方文檔的引用此模塊的聲明書寫:
from docx import *
from docx.shared import Inches
官方文檔:
https://python-docx.readthedocs.io/en/latest/index.html
今天只進行了初略了解,對此模塊對象還沒有深入研究。
四、其它感受
今天已成功解決了昨天沒有解決的寫入sqlite數據庫的問題,而且今天發現,
關系型數據庫的
insert
sql語句應當是可以通用的,那麽完成一個統一的通用添加函數,最好與nosql數據庫都統一起來就更好,這樣對數據存取入數據庫的代碼書寫和記憶來說都要簡化很多。
——————————
今天整理的學習筆記完成,最後例行說明下我的自學思路:
根據過去多年我自學各種編程語言的經歷,認為只有真正體驗式,解決實際問題式的學習才會有真正的效果,即讓學習實際發生。在2004年的時候我開始在一個鄉村小學自學電腦 並學習vb6編程語言,沒有學習同伴,也沒有高師在上,甚至電腦都是孤島(鄉村那時還沒有網絡),有的只是一本舊書,在痛苦的自學摸索中,我找到適應自己零基礎的學習方法:首先是每讀書的一小節就作相應的手寫筆記,第二步就是上機測試每一個筆記內容是否實現,其中會發現書中講的其實有出入或錯誤,第三步就是在上機測試之後,將筆記改為電子版,形成最終的修訂好的正確無誤的學習筆記 。
通過反復嘗試錯誤,在那個沒有分享與交流的黑暗時期我摸黑學會了VB6,爾後接觸了其它語言,也曾聽過付費視頻課程,結果發現也許自己學歷果然太低,就算是零基礎的入門課程,其實也難以跟上進度,講師的教學多數出現對初學者的實際情況並不了解的情況,況且學習者的個體也存在差異呢?當然更可怕的是收費課程的價格往往是自己難以承受的。
於是我的所有編程學習都改為了自學,繼續自己的三步學習筆記法的學習之路。
當然自學的最大問題是會走那麽多的彎路,沒有導師直接輸入式的教學來得直接,好在網絡給我們帶來無限搜索的機會,大家在網絡上的學習日誌帶給我們共享交流的機會,而QQ群等交流平臺、網絡社區的成立,我們可以一起自學,互相批評交流,也可以獲得更有效,更自主的自學成果。
於是我以人生已過半的年齡,決定繼續我的編程自學之路,開始學習python,只希望與大家共同交流,一個人的獨行是可怕的,只有一群人的共同前進才是有希望的。
誠摯期待您的交流分享批評指點!歡迎聯系我加入從零開始的自學聯盟。
這個時代互聯網成為了一種基礎設施的存在,於是本來在孤獨學習之路上的我們變得不再孤獨,因為網絡就是一個新的客廳,我們時刻都可以進行沙龍活動。
非常樂意能與大家一起交流自己自學心得和發現,更希望大家能夠對我學習過程中的錯誤給予指點——是的,這樣我就能有許多免費的高師了——這也是分享時代,社區時代帶來的好福利,我相信大家會的,是吧!
根據完全共享的精神,開源互助的理念,我的個人自學錄制過程是全部按4K高清視頻錄制的,從手寫筆記到驗證手寫筆記的上機操作過程全程錄制,但因為4K高清文件太大均超過5G以上,所以無法上傳至網絡,如有需要可聯系我QQ578652607對傳,樂意分享。上傳分享到百度網盤的只是壓縮後的720P的視頻。
我的學習過程錄像百度盤地址分享如下:(清晰度:1280x720)
鏈接:https://pan.baidu.com/s/1zjlWH2maPabigrLeDnSnbg
提取碼:2adh
Bilibili:
https://www.bilibili.com/video/av40813661/
喜馬拉雅語音筆記:
https://www.ximalaya.com/keji/19103006/154269324
孤荷淩寒自學python第七十五天開始寫Python的第一個爬蟲5