爬蟲(chóng)(五)firefox動(dòng)態(tài)內(nèi)容(知乎(需登錄))

瀏覽器爬蟲(chóng)可以?xún)?nèi)嵌 js 腳本

https://zhuanlan.zhihu.com/p/25214682

登錄方式

  1. 用 cookie 實(shí)現(xiàn)登錄(請(qǐng)求頭),需要提前手動(dòng)登錄
  2. 在登錄窗口自動(dòng)輸入也可以
  3. 利用 firefox 配置文件,里面有網(wǎng)頁(yè)的任何信息(用戶(hù)名密碼等)
    https://support.mozilla.org/en-US/kb/profiles-where-firefox-stores-user-data?redirectlocale=en-US&redirectslug=Profiles
firefox 配置文件.png
配置文件路徑.png
import config
import platform
import os
from splinter import Browser

def add_chrome_webdriver():
    print(platform.system())
    working_path = os.getcwd()
    library = 'library'
    path = os.path.join(working_path, library)
    os.environ['PATH'] += '{}{}{}'.format(os.pathsep, path, os.pathsep)
    print(os.environ['PATH'])

def scroll_to_end(browser):
    browser.execute_script('window.scrollTo(0, document.body.scrollHeight);')
  1. 將驅(qū)動(dòng)加入環(huán)境變量
  2. 將瀏覽器滾動(dòng)條滾動(dòng)到底部,這就是插入 js 事件
def start_crawler():
    option = config.profile

    with Browser(profile=option) as browser:
        url = "https://www.zhihu.com"
        browser.visit(url)
        browser.reload()

        print(browser.html)
        scroll_to_end(browser)
        found = False

        while not found:
            print('loop')
            found = browser.is_text_present('1 天前')
            if found:
                print('拿到了最近1天動(dòng)態(tài)')
                break
            else:
                scroll_to_end(browser)
  • Browser() 的參數(shù) profile 定義 firefox 的配置文件
  • visit() 訪(fǎng)問(wèn) url,然后 reload() 重新加載頁(yè)面(相當(dāng)于刷新),進(jìn)入登錄界面
  • 滑動(dòng)滾動(dòng)條進(jìn)行循環(huán)查找

def main():
    add_chrome_webdriver()
    start_crawler()

if __name__ == '__main__':
    main()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容