爬取动态加载的数据
selenium : 三方库,可以实现让浏览器完成自动化的操作
pip install selnuium
获取浏览器驱动程序
http://chromedriver.storage.googleapis.com/index.html
版本对照表
http://blog.csdn.net/huilan_same/article/details/51896672
# 设置不加载图片 chorme_opt = webdriver.ChromeOptions() prefs = {"profile.managed_default_content_settings.images":2} chrome_opt.add_experimental_options("prefs",prefs) bro = webdriver.Chrome(executable_path=r"C:\Users\ace\Desktop\chromedriver.exe",chrome_options=chrome_opt)
#使用下面的方法,查找指定的元素进行操作即可 find_element_by_id 根据id找节点 find_elements_by_name 根据name找 find_elements_by_xpath 根据xpath查找 find_elements_by_tag_name 根据标签名找 find_elements_by_class_name 根据class名字查找 find_elements_by_link_text 根据链接的text
# 处理弹出的警告页面 确定accept() 和 取消dismiss() bro.switch_to_alert().accept()
js = 'window.scrollTo(0,document.body.scrollHeight)' bro.execute_script(js) # 该函数可以执行一组字符串形式的js代码
html_source = bro.page_source # 该属性可以获取当前浏览器的当前页的源码(html)
iframe = bro.find_element_by_id("kw") bro.switch_to.frame(iframe) # 切换到frame对象 ;也可以直接写id值 bro.switch_to.default_content()# 切换回默认的
from selenium import webdriver
from time import sleep
bro = webdriver.Chrome(executable_path=r"C:\Users\ace\Desktop\chromedriver.exe")
bro.get("https://www.baidu.com")
text = bro.find_element_by_id("kw")
text.send_keys("张三")
bro.find_element_by_id("su").click()
sleep(1)
text.clear()
text.send_keys("张三1")
bro.find_element_by_id("su").click()
sleep(2)
bro.quit()
phantomJs :无界面浏览器 其自动化流程和上述一致,只是没有界面显示,但提供了截图的功能,方便我们查看
已停止更新
from selenium import webdriver
bro = webdriver.PhantomJS(executable_path=r"C:\Users\ace\Desktop\phantomjs.exe")
bro.get("https://www.baidu.com")
bro.save_screenshot("1.png")
text = bro.find_element_by_id("kw")
text.send_keys("张三")
bro.save_screenshot("2.png")
bro.find_element_by_id("su").click()
bro.save_screenshot("3.png")
text.clear()
bro.save_screenshot("4.png")
text.send_keys("张三1")
bro.save_screenshot("5.png")
bro.find_element_by_id("su").click()
bro.save_screenshot("6.png")
bro.quit()
谷歌无头浏览器
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time # 创建一个参数对象,用来控制chrome以无界面模式打开 chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') # 驱动路径 path = r'C:\Users\ZBLi\Desktop\1801\day05\ziliao\chromedriver.exe' # 创建浏览器对象 browser = webdriver.Chrome(executable_path=path, chrome_options=chrome_options) # 上网 url = 'http://www.baidu.com/' browser.get(url) time.sleep(3) browser.save_screenshot('baidu.png') browser.quit()