適合本篇閱讀的人:
範例流程:
爬取python Taiwan FB社團,在社團內部自動垂直瀏覽頁面 。 爬取貼文時間,併計算貼文數量。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import selenium
from selenium import webdriver
from bs4 import BeautifulSoup
import numpy as np
import time
import csv
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver=webdriver.Chrome("./chromedriver",chrome_options=chrome_options)
driver.get("https://www.facebook.com/groups/pythontw/")
post=[]
soup=BeautifulSoup(driver.page_source,"lxml")
first=soup.find_all(class_="text_exposed_root")
for i in first:
post.append(i.text)
timme=soup.find_all("abbr")
real=[]
for i in timme:
if i.get("title")!=None:
real.append(i.get("title"))
while real[-1].split(" ")[0]!="2019/9/3":
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
post=[]
soup=BeautifulSoup(driver.page_source,"lxml")
first=soup.find_all(class_="text_exposed_root")
for i in first:
post.append(i.text)
timme=soup.find_all("abbr")
real=[]
for i in timme:
if i.get("title")!=None:
real.append(i.get("title"))
print(real[-1].split(" ")[0])
print(len(post))
driver.close()
View the code on Gist . 第一部分:介紹各種python內建套件模塊
1. Selenium:程序可以直接驅動瀏覽器進行各種網站操作。
2. Webdriver:真實的模擬人對於瀏覽器的操作行為。
3. BeautifulSoup:最主要的功能是從網頁抓取數據。
4. numpy:多維數據集數學函式庫。
5.time:獲取當前的時間,操作時間和日期,從串行讀取時間及格式化時間為字符串。
6. Csv:在Python中可以讀取或產生csv的檔案。
第二部分:啟動瀏覽器,進入指定的網址頁面
每次當硒啟動chrome瀏覽器的時候,chrome流覽器很乾淨,沒有外掛程式,沒有收藏,沒有歷史記錄,
這是因為硒在啟動chrome時為了保證快速的運行效率,啟動了一個裸流覽器,這就是為什麼需要配置參數的原因。
selenium啟動配置參數接收是ChromeOptions類,創建方式如下:
第三部分:爬取網頁資料
l 爬取社團中所有所有貼文
l爬取至2020/2/1的 貼文時間,並算出社團總貼文數
小結: 這樣就完成了一個FB社團的網頁爬取!
最後,喜歡我的文章幫我拍拍手,給予我鼓勵我會很開心的
Python初學總整理 全系列:
Python初學總整理 第1講:Python簡介
Python初學總整理 第2講:Python開發環境
Python初學總整理 第3講:Python資料型態和運算子
Python初學總整理 第4講:Python條件、迴圈與函數
Python初學總整理 第5講:爬蟲應用(上)
Python初學總整理 第6講:爬蟲應用(下)
Python初學總整理 第7講:爬蟲實例解析 – 以爬取臉書社團為案例,使用 Selenium 來進行網頁模擬爬蟲 (本篇)
Python初學總整理 第8講:Matplotlib套件
Python初學總整理 第9講:Numpy函式庫
文章看完還是不知道該從哪裡下手? 就從線上課程開始吧!不讓你獨自摸索好幾個月,用8小時帶你走完基礎與精華,培養你基礎的Python概念,讓自學下一步不是煩惱!
全新Python 課程上架,8小時基礎實戰!,限時優惠只要NT 600 (HDK 120 起)!
不讓妳浪費一整天,只要你8小時,就能讓你學會基礎!
現在開始上課!
如果你的入門還在單打獨鬥,歡迎來到快樂學程式找到志同道合的夥伴 ,你的自學之路不孤單。
快樂學程式