python+selenium爬取微博熱搜存入Mysql的實現方法
最終的效果
廢話不多少,直接上圖
這里可以清楚的看到,數據庫里包含了日期,內容,和網站link下面我們來分析怎么實現
使用的庫import requestsfrom selenium.webdriver import Chrome, ChromeOptionsimport timefrom sqlalchemy import create_engineimport pandas as pd
目標分析
這是微博熱搜的link:點我可以到目標網頁
首先我們使用selenium對目標網頁進行請求然后我們使用xpath對網頁元素進行定位,遍歷獲得所有數據然后使用pandas生成一個Dataframe對像,直接存入數據庫
一:得到數據我們看到,使用xpath可以得到51條數據,這就是各熱搜,從中我們可以拿到鏈接和標題內容
all = browser.find_elements_by_xpath(’//*[@id='pl_top_realtimehot']/table/tbody/tr/td[2]/a’) #得到所有數據context = [i.text for i in c] # 得到標題內容 links = [i.get_attribute(’href’) for i in c] # 得到link
然后我們再使用zip函數,將date,context,links合并zip函數是將幾個列表合成一個列表,并且按index對分列表的數據合并成一個元組,這個可以生產pandas對象。
dc = zip(dates, context, links) pdf = pd.DataFrame(dc, columns=[’date’, ’hotsearch’, ’link’])
其中date可以使用time模塊獲得
二:鏈接數據庫這個很容易
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(’出錯了’)if __name__ == ’__main__’: xx = get_data() w_mysql(xx)
到此這篇關于python+selenium爬取微博熱搜存入Mysql的實現方法的文章就介紹到這了,更多相關python selenium爬取微博熱搜存入Mysql內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
