python+selenium爬取微博熱搜存入Mysql的實(shí)現(xiàn)方法
最終的效果
廢話不多少,直接上圖
這里可以清楚的看到,數(shù)據(jù)庫里包含了日期,內(nèi)容,和網(wǎng)站link下面我們來分析怎么實(shí)現(xiàn)
使用的庫import requestsfrom selenium.webdriver import Chrome, ChromeOptionsimport timefrom sqlalchemy import create_engineimport pandas as pd
目標(biāo)分析
這是微博熱搜的link:點(diǎn)我可以到目標(biāo)網(wǎng)頁
首先我們使用selenium對目標(biāo)網(wǎng)頁進(jìn)行請求然后我們使用xpath對網(wǎng)頁元素進(jìn)行定位,遍歷獲得所有數(shù)據(jù)然后使用pandas生成一個(gè)Dataframe對像,直接存入數(shù)據(jù)庫
一:得到數(shù)據(jù)我們看到,使用xpath可以得到51條數(shù)據(jù),這就是各熱搜,從中我們可以拿到鏈接和標(biāo)題內(nèi)容
all = browser.find_elements_by_xpath(’//*[@id='pl_top_realtimehot']/table/tbody/tr/td[2]/a’) #得到所有數(shù)據(jù)context = [i.text for i in c] # 得到標(biāo)題內(nèi)容 links = [i.get_attribute(’href’) for i in c] # 得到link
然后我們再使用zip函數(shù),將date,context,links合并zip函數(shù)是將幾個(gè)列表合成一個(gè)列表,并且按index對分列表的數(shù)據(jù)合并成一個(gè)元組,這個(gè)可以生產(chǎn)pandas對象。
dc = zip(dates, context, links) pdf = pd.DataFrame(dc, columns=[’date’, ’hotsearch’, ’link’])
其中date可以使用time模塊獲得
二:鏈接數(shù)據(jù)庫這個(gè)很容易
enging = create_engine('mysql+pymysql://root:123456@localhost:3306/webo?charset=utf8')pdf.to_sql(name=’infromation’, con=enging, if_exists='append')
總代碼
from selenium.webdriver import Chrome, ChromeOptionsimport timefrom sqlalchemy import create_engineimport pandas as pddef get_data(): url = r'https://s.weibo.com/top/summary' # 微博的地址 option = ChromeOptions() option.add_argument(’--headless’) option.add_argument('--no-sandbox') browser = Chrome(options=option) browser.get(url) all = browser.find_elements_by_xpath(’//*[@id='pl_top_realtimehot']/table/tbody/tr/td[2]/a’) context = [i.text for i in all] links = [i.get_attribute(’href’) for i in all] date = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime()) dates = [] for i in range(len(context)): dates.append(date) # print(len(dates),len(context),dates,context) dc = zip(dates, context, links) pdf = pd.DataFrame(dc, columns=[’date’, ’hotsearch’, ’link’]) # pdf.to_sql(name=in, con=enging, if_exists='append') return pdfdef w_mysql(pdf): try: enging = create_engine('mysql+pymysql://root:123456@localhost:3306/webo?charset=utf8') pdf.to_sql(name=’infromation’, con=enging, if_exists='append') except: print(’出錯(cuò)了’)if __name__ == ’__main__’: xx = get_data() w_mysql(xx)
到此這篇關(guān)于python+selenium爬取微博熱搜存入Mysql的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)python selenium爬取微博熱搜存入Mysql內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. 教你在 IntelliJ IDEA 中使用 VIM插件的詳細(xì)教程3. IntelliJ IDEA導(dǎo)入jar包的方法4. js抽獎(jiǎng)轉(zhuǎn)盤實(shí)現(xiàn)方法分析5. Python requests庫參數(shù)提交的注意事項(xiàng)總結(jié)6. vue-electron中修改表格內(nèi)容并修改樣式7. iOS實(shí)現(xiàn)點(diǎn)贊動(dòng)畫特效8. 通過Python pyecharts輸出保存圖片代碼實(shí)例9. SpringBoot參數(shù)校驗(yàn)與國際化使用教程10. PHP橋接模式Bridge Pattern的優(yōu)點(diǎn)與實(shí)現(xiàn)過程
