久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

python+selenium爬取微博熱搜存入Mysql的實(shí)現(xiàn)方法

瀏覽:12日期:2022-06-29 08:20:33

最終的效果

廢話不多少,直接上圖

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)頁

python+selenium爬取微博熱搜存入Mysql的實(shí)現(xiàn)方法

首先我們使用selenium對目標(biāo)網(wǎng)頁進(jìn)行請求然后我們使用xpath對網(wǎng)頁元素進(jìn)行定位,遍歷獲得所有數(shù)據(jù)然后使用pandas生成一個(gè)Dataframe對像,直接存入數(shù)據(jù)庫

一:得到數(shù)據(jù)

python+selenium爬取微博熱搜存入Mysql的實(shí)現(xiàn)方法

我們看到,使用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)!

標(biāo)簽: 微博 Python
相關(guān)文章:
主站蜘蛛池模板: 禄丰县| 迁西县| 丹巴县| 巴楚县| 汽车| 胶南市| 青龙| 当涂县| 呼图壁县| 上杭县| 全南县| 东阳市| 长乐市| 潼南县| 贵阳市| 小金县| 上高县| 鸡东县| 昌图县| 开阳县| 南汇区| 安西县| 惠州市| 西青区| 吴川市| 临汾市| 汉川市| 青海省| 崇仁县| 颍上县| 海晏县| 镇原县| 成安县| 肇源县| 文安县| 青岛市| 卢龙县| 扎囊县| 牟定县| 张家川| 当雄县|