Selenium簡介與安裝
Selenium是什么?
Selenium也是一個用于Web應(yīng)用程序測試的工具。Selenium測試直接運(yùn)行在瀏覽器中,就像真正的用戶在操作一樣。支持的瀏覽器包括IE、Mozilla Firefox、Mozilla Suite等。
安裝
直接使用pip命令安裝即可!
pip install selenium
Python抓取微博有兩種方式,一是通過selenium自動登錄后從頁面直接爬取,二是通過api。
這里采用selenium的方式。
程序:
from selenium import webdriverimport timeimport re#全局變量driver = webdriver.Chrome("C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe")def loginWeibo(username, password):  driver.get('https://passport.weibo.cn/signin/login')  time.sleep(1)  driver.find_element_by_id("loginName").send_keys("haishu_zheng@163.com")  driver.find_element_by_id("loginPassword").send_keys("Weibo01061122")  time.sleep(1)  driver.find_element_by_id("loginAction").click()  #driver.close()  def visitUserPage(userId):  driver.get('http://weibo.cn/' + userId)  print('********************')    print('用戶資料')    # 1.用戶id  print('用戶id:' + userId)    # 2.用戶昵稱  strName = driver.find_element_by_xpath("//div[@class='ut']")  strlist = strName.text.split(' ')  nickname = strlist[0]  print('昵稱:' + nickname)    # 3.微博數(shù)、粉絲數(shù)、關(guān)注數(shù)  strCnt = driver.find_element_by_xpath("//div[@class='tip2']")  pattern = r"/d+/.?/d*" # 匹配數(shù)字,包含整數(shù)和小數(shù)  cntArr = re.findall(pattern, strCnt.text)  print(strCnt.text)  print("微博數(shù):" + str(cntArr[0]))  print("關(guān)注數(shù):" + str(cntArr[1]))  print("粉絲數(shù):" + str(cntArr[2]))    print('/n********************')  # 4.將用戶信息寫到文件里  with open("weibo.txt", "w", encoding = "gb18030") as file:    file.write("用戶ID:" + userId + '/r/n')    file.write("昵稱:" + nickname + '/r/n')    file.write("微博數(shù):" + str(cntArr[0]) + '/r/n')    file.write("關(guān)注數(shù):" + str(cntArr[1]) + '/r/n')    file.write("粉絲數(shù):" + str(cntArr[2]) + '/r/n')      # 5.獲取微博內(nèi)容  # http://weibo.cn/ + userId + ? filter=0&page=1  # filter為0表示全部,為1表示原創(chuàng)  print("微博內(nèi)容")    pageList = driver.find_element_by_xpath("//div[@class='pa']")  print(pageList.text)  pattern = r"/d+/d*"     # 匹配數(shù)字,只包含整數(shù)  pageArr = re.findall(pattern, pageList.text)  totalPages = pageArr[1]   # 總共有多少頁微博  print(totalPages)    pageNum = 1     # 第幾頁  numInCurPage = 1      # 當(dāng)前頁的第幾條微博內(nèi)容  contentPath = "//div[@class='c'][{0}]"  while(pageNum <= 3):    #while(pageNum <= int(totalPages)):    contentUrl = "http://weibo.cn/" + userId + "?filter=0&page=" + str(pageNum)    driver.get(contentUrl)    content = driver.find_element_by_xpath(contentPath.format(numInCurPage)).text    # print("/n" + content) # 微博內(nèi)容,包含原創(chuàng)和轉(zhuǎn)發(fā)    if "設(shè)置:皮膚.圖片.條數(shù).隱私" not in content:      numInCurPage += 1      with open("weibo.txt", "a", encoding = "gb18030") as file:        file.write("/r/n" + "/r/n" + content)  # 將微博內(nèi)容逐條寫到weibo.txt中    else:      pageNum += 1            # 抓取新一頁的內(nèi)容      numInCurPage = 1          # 每一頁都是從第1條開始抓        if __name__ == '__main__':  username = 'haishu_zheng@163.com'  # 輸入微博賬號  password = 'Weibo01061122'     # 輸入密碼  loginWeibo(username, password)   # 要先登錄,否則抓取不了微博內(nèi)容  time.sleep(3)  uid = 'xywyw'            # 尋醫(yī)問藥  visitUserPage(uid)運(yùn)行結(jié)果:
同時還生成了weibo.txt文件,內(nèi)容如下
這種方法有個缺陷,就是爬取較多內(nèi)容會被封IP:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選