爬虫selenium教程

'''
在爬取某些网站时有js加载的信息时,主要是js拼接的操作,
可以通过selenium来进行拼接,可以节省大量的破解JS还原操作的时间,
大大节省成本;

安装selenium:
pip install Selenium

安装chromedriver:

查看当前浏览器版本
输入chrome://help/ 可以看到“版本 68.0.3440.106(正式版本) (32 位)”字样


查看版本对应的驱动(翻墙摸摸哒)
https://sites.google.com/a/chromium.org/chromedriver/downloads

找到对应的驱动版本点击进去,选择下载

#https://chromedriver.storage.googleapis.com/index.html 所有版本库的下载链接

对于window版本:(举例)
直接解压出里面的文件放到"C:/chromedriver"下,
将该路径配置到环境变量中。
否则会报“selenium.common.exceptions.WebDriverException”的错误


>>> from selenium import webdriver

#头三行可以不启动浏览器提升速度
>>> option = webdriver.ChromeOptions()
>>> option.add_argument("headless")
>>> driver = webdriver.Chrome(chrome_options=option)

>>> driver.get("https://www.zymk.cn/2446/145198.html")
>>> driver.page_source#返回JS渲染过后网页源代码


#对于一些JS要一边滑行一边加载的情况我用以下方法来实现滑动动作。

>>> from selenium import webdriver

>>> from selenium.webdriver.common.action_chains import ActionChains #


>>> driver = webdriver.Chrome()

>>> driver.get("https://ac.qq.com/ComicView/index/id/629846/cid/1")

#到这里我们发现该网站是要滑动浏览器的滚动条来触发js对图片一个个进行加载,
#我们下面做个模仿拉动支滚动条的动作

>>> above = driver.find_element_by_id("mainControlNext")# 定位到要悬停的元素。

>>> ActionChains(driver).move_to_element(above).perform()# 对定位到的元素执行鼠标悬停操作

>>> driver.page_source#返回JS渲染过后网页源代码

#另处一种原理是借助JavaScript来控制浏览器的滚动条。
#WebDriver提供了execute_script()方法来执行JavaScript代码。
#<!-- window.scrollTo(左边距,上边距); -->window.scrollTo(0,450)
#更多可参考:https://blog.csdn.net/lilongsy/article/details/76142497

>>> js="window.scrollTo(0,2000);"

>>> driver.execute_script(js)

>>> driver.quit()

对于爬虫来说selenium主要用法已经完成,其他相关的selenium操作文档参考如下:


中文:http://www.testclass.net/selenium_python/

'''

原文地址:https://www.cnblogs.com/cwx-0324/p/10193970.html