信息技術手冊可視化進度報告 基於BeautifulSoup框架的python3爬取數據並連接保存到MySQL數據庫
阿新 • • 發佈:2019-03-23
解釋 return oot 進度 mysql recursive div == lec
老師給我們提供了一個word文檔,裏面是一份信息行業熱詞解釋手冊,要求我們把裏面的文字存進數據庫裏面,然後在前臺展示出來。
首先面臨的問題是怎麽把數據導進MySQL數據庫,大家都有自己的方法,我采用了將word轉換成html文件,然後通過爬蟲技術將內容提取出來保存到數據庫。
寫這篇博客的時候我剛存進數據庫裏,所以就介紹一下我的爬蟲代碼,下一篇將介紹通過微信小程序展示MySQL中的數據。
python的爬蟲框架有很多,我用的是BeautifulSoup框架,首先要在頭文件引用一下包from bs4 import BeautifulSoup
BeautifulSoup框架常用的用的一些函數有:
find()#獲得一條map數據
find_all(name , attrs , recursive , string , **kwargs )#搜索當前tag的所有tag子節點,並判斷是否符合過濾器的條件,獲得list列表
select()#跟find_all類似,常用的是find_all(),可以通過select(‘#id‘)取得含有特定CSS屬性的元素
get_text()#返回一個tag節點內的文字
同學也有用xpath做爬蟲的
XPath 是一門在 XML 文檔中查找信息的語言。
BeautifulSoup是一種在BeautifulSoup()處理後的樹形文檔中解析的語言re正則表達式只能對string類型對象進行解析
下面是代碼
from bs4 import BeautifulSoup import pymysql #數據時從本地文件裏來 def read_file(path): #註意編碼格式可能會出錯 with open(path, ‘r+‘, encoding=‘ANSI‘) as f: str = f.read() return str.strip().replace(‘\ufeff‘, ‘‘) # 解析目錄數據 def parse_data(data): #讀取第一個MsoToc1和第二個MsoToc1之間的所有數據 for str1 in data.split(‘class=MsoToc1‘)[1:]: bs = BeautifulSoup(str1, ‘lxml‘) index = 0 title1 = "" title2 = "" title3 = "" try: for tag in bs.select(‘a‘): strs = tag.get_text().split(‘ ‘)[0].rstrip() if (‘第‘ in strs and ‘篇‘ in strs): title1 = tag.get_text().split(‘ ‘)[1].replace(‘.‘, ‘‘) elif (‘第‘ in strs and ‘章‘ in strs): title2 = tag.get_text().split(‘ ‘)[1].replace(‘.‘, ‘‘) else: index = strs; title3 = tag.get_text().split(‘ ‘)[1].replace(‘.‘, ‘‘) save(index, title1, title2, title3) except: print("數據有誤,跳過執行") bigdiv = data.split(‘class=WordSection3‘)[1] for str1 in bigdiv.split(‘class=3132020‘)[1:]: soup = BeautifulSoup(‘<p class=3132020 ‘+str1, ‘lxml‘) content = "" index = int(soup.find(‘p‘, {‘class‘: ‘3132020‘}).get_text().split(‘ ‘)[0]) for tag in soup.find_all(‘p‘, {‘class‘: ‘4‘}): content += tag.get_text()+‘\r\n‘ update(index,content) return #保存到數據庫 def save(index,title1,title2,title3): db = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘root‘, db=‘jaovo_msg‘) conn = db.cursor() # 獲取指針以操作數據庫 conn.execute(‘set names utf8‘) t = (int(index), title1, title2, title3) sql = "INSERT INTO datasfromhtml(`index`,title1,title2,title3) values(%d,‘%s‘,‘%s‘,‘%s‘)" % t try: conn.execute(sql) # 執行sql語句 db.commit() except: # 發生錯誤時回滾 db.rollback() # 關閉數據庫連接 db.close() return #修改到數據庫 def update(index,content): db = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘root‘, db=‘jaovo_msg‘) conn = db.cursor() # 獲取指針以操作數據庫 conn.execute(‘set names utf8‘) t = (content,int(index)) sql = "update datasfromhtml set content = ‘%s‘ where `index` = %d" % t try: conn.execute(sql) # 執行sql語句 db.commit() except: # 發生錯誤時回滾 db.rollback() # 關閉數據庫連接 db.close() return if __name__ == ‘__main__‘: str=read_file(‘../resource/HB.htm‘) parse_data(str)
信息技術手冊可視化進度報告 基於BeautifulSoup框架的python3爬取數據並連接保存到MySQL數據庫