第一步:python中安裝selenium庫
和其他所有Python庫一樣,selenium庫需要安裝
pip install selenium # Windows電腦安裝selenium
pip3 install selenium # Mac電腦安裝selenium
第二步:下載谷歌瀏覽器驅動并合理放置
selenium的腳本可以控制所有常見瀏覽器,在使用之前需要安裝瀏覽器端的驅動
注意:驅動和瀏覽器要版本對應
推薦使用Chrome瀏覽器:谷歌瀏覽器驅動
打開chrome瀏覽器,在網址欄中輸入chrome://version/打開關于版本頁面,根據版本信息下載相應chrome驅動
將驅動放在python的安裝目錄(我的python集成在Anaconda3)
第三步:使用selenium爬取QQ音樂歌詞(簡單示例)
import time
# 本地Chrome瀏覽器設置方法
from selenium import webdriver #從selenium庫中調用webdriver模塊
driver = webdriver.Chrome() # 設置引擎為Chrome,從本地打開一個Chrome瀏覽器
driver.get('https://y.qq.com/n/ryqq/songDetail/0002Pa3i2ZU2Ec') # 打開網頁
time.sleep(3) # 程序暫停3秒鐘,等待網頁加載完畢
div_p = driver.find_element_by_id('lrc_content') # 解析網頁并提取所需標簽
print(div_p.text) # 打印文本
driver.close() # 關閉瀏覽器

小結
到此這篇關于python怎么使用selenium庫的文章就介紹到這了,更多selenium庫的使用教程請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關文章。