zoukankan      html  css  js  c++  java
  • selenium:指挥浏览器工作

    selenium可以用几行代码,控制浏览器,做出自动打开、输入、点击等操作,就像是有一个真正的用户在操作一样。

    在遇到页面交互复杂或是URL加密逻辑复杂的情况时,selenium就派上了用场,它可以真实地打开一个浏览器,等待所有数据都加载到Elements中之后,再把这个网页当做静态网页爬取就好了。

    安装

    pip install selenium

    配置驱动

    推荐的是Chrome浏览器,打开下面的链接,就可以下载Chrome的安装包了,Windows和Mac都有:

    https://localprod.pandateacher.com/python-manuscript/crawler-html/chromedriver/ChromeDriver.html

    其他浏览器驱动的下载地址:

    Firefox浏览器驱动:geckodriver

    IE浏览器驱动:IEDriverServer

    Edge浏览器驱动:MicrosoftWebDriver

    Opera浏览器驱动:operadriver

    PhantomJS浏览器驱动:phantomjs

    下载的驱动,要放在Python路径旁,即可正常使用驱动

    简单案例

    1.自动填充内容,并触发按钮的点击:

    from selenium import webdriver
    import time
    
    # 设置浏览器引擎
    driver = webdriver.Chrome()
    
    # 请求网页
    url = 'https://localprod.pandateacher.com/python-manuscript/hello-spiderman/'
    driver.get(url)
    time.sleep(2)
    
    # 获取输入框,并填充内容
    teacher = driver.find_element_by_id('teacher')
    # 输入文字
    teacher.send_keys('酱酱')
    
    # 获取输入框,并填充内容
    assistant = driver.find_element_by_name('assistant')
    # 输入文字
    assistant.send_keys('都喜欢')
    
    time.sleep(2)
    
    # 清除元素内容
    teacher.clear()
    time.sleep(2)
    teacher.send_keys('蜘蛛侠')
    
    # 获取按钮,并触发点击事件
    sub = driver.find_element_by_class_name('sub')
    # 点击按钮
    sub.click()
    
    time.sleep(2)
    
    # 关闭浏览器
    driver.close()

    2.爬取QQ音乐精彩评论:

    使用的是静默模式(浏览器默默运行,并不会弹出)

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    import time
    
    # 设置静默模式
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    
    # driver = webdriver.Chrome()
    driver = webdriver.Chrome(options=chrome_options) # 浏览器在后台默默运行
    print('正请求网页内容...')
    driver.get('https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html')
    time.sleep(2)
    
    print('加载更多...')
    # 点击加载更多
    more_hot_btn = driver.find_element_by_class_name('js_get_more_hot')
    more_hot_btn.click()
    
    time.sleep(1)
    
    print('获取评论...')
    # 获取评论
    comments = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li')
    for comment in comments:
        print(comment.find_element_by_class_name('js_hot_text').text)
        print("")
    
    driver.close()

    其他资料:

    1.selenium官方文档:https://selenium.dev/selenium/docs/api/py/api.html

    2.selenium中文翻译文档:https://selenium-python-zh.readthedocs.io/en/latest/

    3.设置浏览器驱动:https://www.cnblogs.com/muxs/p/11346740.html

    4.基础入门:https://www.jianshu.com/p/1531e12f8852

  • 相关阅读:
    线程池源码解析
    String与常量池
    spring循环依赖
    ConcurrentHashMap源码解析(JDK8)
    原子类源码分析
    web service和ejb的区别
    RPC
    hashcode()和equals()的区别
    关于json
    Lifecycle of jsf
  • 原文地址:https://www.cnblogs.com/KeenLeung/p/12208487.html
Copyright © 2011-2022 走看看