### 資料綱目 1. product_name: 商品名稱 2. product_price_NTD: 商品價格 3. product_link: 商品連結 4. product_image: 商品圖片 ### 滑鼠游標放置於網頁元素中間 Python 網路爬蟲與資料視覺化 > 7-27 & 7-28 ### 從網路上下載圖檔 Python 網路爬蟲與資料視覺化 > 5-28 ### 反反爬蟲 > 設定 Request Headers https://www.learncodewithmike.com/2020/09/7-tips-to-avoid-getting-blocked-while-scraping.html ``` import requests headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-TW,zh;q=0.9", "Host": "example.com", #目標網站 "Sec-Fetch-Dest": "document", "Sec-Fetch-Mode": "navigate", "Sec-Fetch-Site": "none", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36" #使用者代理 } response = requests.get(url="https://example.com", headers=headers) ``` ### 反反爬蟲 > 設定 User-Agent https://www.learncodewithmike.com/2020/09/7-tips-to-avoid-getting-blocked-while-scraping.html ``` import requests from fake_useragent import UserAgent user_agent = UserAgent() response = requests.get(url="https://example.com", headers={ 'user-agent': user_agent.random }) ``` ### 反反爬蟲 > 取消網頁中的彈出視窗 ``` from selenium.webdriver.chrome.options import Options import time options = Options() options.add_argument("--disable-notifications") ``` ### 反反爬蟲 > 設定 Options https://zhuanlan.zhihu.com/p/60852696 ``` from selenium import webdriver option = webdriver.ChromeOptions() # 設定 user-agent options.add_argument("user-agent=Your_Custom_User_Agent_String") # 添加UA options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"') # 指定浏览器分辨率 options.add_argument('window-size=1920x3000') # 谷歌文档提到需要加上这个属性来规避bug chrome_options.add_argument('--disable-gpu') # 隐藏滚动条, 应对一些特殊页面 options.add_argument('--hide-scrollbars') # 不加载图片, 提升速度 options.add_argument('blink-settings=imagesEnabled=false') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败 options.add_argument('--headless') # 以最高权限运行 options.add_argument('--no-sandbox') # 手动指定使用的浏览器位置 options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" #添加crx插件 option.add_extension('d:\crx\AdBlock_v2.17.crx') # 禁用JavaScript option.add_argument("--disable-javascript") # 设置开发者模式启动,该模式下webdriver属性为正常值 options.add_experimental_option('excludeSwitches', ['enable-automation']) # 禁用浏览器弹窗 prefs = { 'profile.default_content_setting_values' : { 'notifications' : 2 } } options.add_experimental_option('prefs',prefs) driver=webdriver.Chrome(chrome_options=chrome_options) ``` ### CSS Selector 1. 選取包含特定字串的 `<div>` `div:contains('特定字串')`   2. 選取 `<div class="test">` 的下一個 `<div>` `div.test + div`