網路爬蟲 自學筆記 (1)

安裝Anaconda

建立虛擬環境

安裝必要的lib

指令:pip install selenium beautifulsoup4 requests pandas-datareader mpl_finance

下載Chroem Driver

網址:https://chromedriver.chromium.org/
請下載跟自己的chrome相符合的版本。

練習Python中的文字操作

字串分割

用法
s.split()
說明
默認以空格、換行字元分割字串s,返回 list

字串合併 將 list 元素合併成字串

用法
s.join(seq)
說明
以string為分隔符,將seq中的元素串起來成為一個新的字串

搜尋字串

用法
s.find(str)
說明
返回s第一次在字串s中出現的index,若找不到則返回-1

替換字串

用法
s.replace(str1, str2)
說明
將s中的str1替換成str2

字串變成小寫

用法
s.lower()
說明
將字串s裡的字母全部改成小寫

字串變成大寫

用法
s.upper()
說明
將字串s裡的字母全部改成大寫

去除字串左邊空格

用法
s.lstrip()
說明
去除字串s左邊的空格

去除字串右邊空格

用法
s.rstrip()
說明
去除字串s右邊的空格

去除字串兩側空格

用法
s.strip()
說明
去除字串s左、右兩邊的空格

List操作練習

初始化一個 list

ids = [1, 2, 3]

新增元素

append
ids.append(4)

修改元素

ids[2] = 5

刪除元素

ids.pop(1)

新增元素在某元素之後

用法
ids.insert(1, 9)
list.insert(index, elememt)
說明
If index is 0, the element is inserted at the beginning of the list.
If index is 3, the element is inserted after the 3rd element. Its position will be 4th.

移除指定的元素

ids.remove(1)

字典練習

初始化字典

dict01 = {“蘋果”: 100, “橘子”: 20, “水梨”: 50}

# 格式化成字串來輸出
# 1. 將所有 keys 轉成 list
list_keys = list(dict01.keys())
# 2. 將所有 values 轉成 list
list_values = list(dict01.values())
# 3. 使用迴圈來輸出格式化字串
for i in range(len(list_keys)):
    print("%s 的價格是 %d 元"%( list_keys[i], list_values[i] ))

if邏輯判斷

  • if…
  • if… elif…
  • if… elif… else…
  • Nested if

條件運算式

x if C else y

while loop

count = 1
while count <= 5:
    print(count, end="")
    count = count + 1

for loop

break, continue

網址操作

使用套件 urllib

# 匯入套件
from urllib import parse

# urlparse
url = 'https://docs.python.org/3.7/search.html?q=parse&check_keywords=yes&area=default'
parseResult = parse.urlparse(url)
print("分析 URLs 成為 components:\n{}".format(parseResult))
# 分析 URLs 成為 components:
# ParseResult(scheme='https', netloc='docs.python.org', path='/3.7/search.html', params='', query='q=parse&check_keywords=yes&area=default', fragment='')


# 印出 scheme
print(parseResult.scheme)
# https


# 印出 query
print(parseResult.query)
# q=parse&check_keywords=yes&area=default

# 產生 url
string = 'https://find.ruten.com.tw/s/?'
query = {
    "q": "iphone12", 
    "p": 2}
result = string + parse.urlencode(query)
print(result)
# https://find.ruten.com.tw/s/?q=iphone12&p=2

使用chromedriver, selenium開啟chrome瀏覽器

'''
匯入套件
'''
# 操作 browser 的 API
from selenium import webdriver

# 處理逾時例外的工具
from selenium.common.exceptions import TimeoutException

# 面對動態網頁,等待某個元素出現的工具,通常與 exptected_conditions 搭配
from selenium.webdriver.support.ui import WebDriverWait

# 搭配 WebDriverWait 使用,對元素狀態的一種期待條件,若條件發生,則等待結束,往下一行執行
from selenium.webdriver.support import expected_conditions as EC

# 期待元素出現要透過什麼方式指定,通常與 EC、WebDriverWait 一起使用
from selenium.webdriver.common.by import By

# 強制等待 (執行期間休息一下)
from time import sleep

# 整理 json 使用的工具
import json

# 執行 command 的時候用的
import os

driver = webdriver.Chrome()
'''
selenium 啓動 Chrome 的進階配置參數
參考網址:https://stackoverflow.max-everyday.com/2019/12/selenium-chrome-options/
'''
# 啟動瀏覽器工具的選項
# options.add_argument("--headless")                #不開啟實體瀏覽器背景執行
options.add_argument("--start-maximized")         #最大化視窗
options.add_argument("--incognito")               #開啟無痕模式
options.add_argument("--disable-popup-blocking ") #禁用彈出攔截

# 使用 Chrome 的 WebDriver (含 options)
driver = webdriver.Chrome( options = options )

# 螢幕最大化
#driver.maximize_window()

# 放置爬取的資料
listData = []