Selenium+PhantomJS使用出错以及解决方案

问题

在学习使用selenium+PhantomJS来爬取网页的时候,刚刚运行就出现了下面的报错信息:

UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '

大概意思就是说新版本的Selenium不再支持PhantomJS了,要求使用Chrome或者Firefox的无头版本来替代,估摸着后面所有的Selenium版本都不会再支持PhantomJS

解决办法

1,使用老版本的Selenium

通过  pip list 来查看自己下载的selenium是哪个版本的,使用  pip uninstall selenium 来卸载 , 然后指定安装2.48版本的selenium    pip install selenium==2.48  ,  这样的话再运行对应的代码应该是不会有问题的

2,使用无界面浏览器

这里我电脑只安装了Chrome浏览器,所有我用的是  selenium + Headless Chrome

前提条件:

       1,电脑需要安装Chrome浏览器

       2,本地需要有chromedriver驱动器文件,其实和PhantomJS一样,如果不配置环境变量的话需要手动指定executable_path参数。

示例代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def main():
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(executable_path='chromedriver', chrome_options=chrome_options)
    driver.get("https://www.baidu.com")
    print(driver.page_source)
    driver.close()


if __name__ == '__main__':
    main()

上面代码需要注意的是,既然chromedriver的用法和PhantomJS差不多,那么只需要把下载好的chromedriver.exe放到你python的根目录下就可以使用了,上面代码的executable_path不添加也没有问题,chrome_options=chrome_options不指定的话运行代码则会出现一个新的Chrom窗口。

Headless Chrome 对 Chrome版本要求 ---->官方文档

官方文档中介绍,maclinux 环境要求chrome版本是59+, 而windows版本的chrome要求是60+

还有一个需要注意的是,不同版本的Chrome对应的chromedriver版本也是不同的, 我的Chrom版本是68.0的所以对应的chromedriver版本是2.41,其他版本的对应关系可以去官网查找下

参考:https://blog.csdn.net/u010358168/article/details/79749149

待续。。。

例:

根据从零开始学Python网络爬虫教学这本书的关于Selenium+PhantomJS的案例来改写的Selenium+headless Chrome,(毕竟新版本的Selenium已经不支持PhantomJS了)来爬取淘宝的数据,然后存到MongoDB数据库中。

# -*- encoding:utf8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from lxml import etree
import pymongo
import time

client = pymongo.MongoClient("localhost", 27017)
mydb = client["mydb"]   # 新建mydb数据库
taobao = mydb["taobao"]     # 新建taobao数据集合

chrome_options = Options()
# 添加启动参数
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 添加了chrome_options 后则会不显示出Chrome窗口,没有添加的话运行会跳出Chrome窗口
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.maximize_window()


def get_info(url, page):
    page = page+1
    driver.get(url)
    selector = etree.HTML(driver.page_source)
    # 这里的xpath是找到class='item'的div标签, 然后找到他下面class='J_MouserOnverReq'的div,只有相同标签才这么写
    infos = selector.xpath("//div[@class='item J_MouserOnverReq  ']")
    # 这里获取的是搜索内容的 图片,价格,超链接,标题,店铺名
    for info in infos:
        data = info.xpath("div/div/a")[0]
        # 当遇到标签套标签的情况时,想要同时爬取文本内容,可以使用string(.)来获取
        title = data.xpath("string(.)").strip()
        price = info.xpath("div/div/div/strong/text()")[0]
        sell = info.xpath('div/div/div[@class="deal-cnt"]/text()')[0]
        shop = info.xpath('div[2]/div[3]/div[1]/a/span[2]/text()')[0]
        address = info.xpath('div[2]/div[3]/div[2]/text()')[0]
        commodity = {
            'title': title,
            'price': price,
            'sell': sell,
            'shop': shop,
            'address': address
        }
        taobao.insert_one(commodity)
    if page <= 10:
        NextPage(url, page)
    else:
        driver.close()


def NextPage(url, page):
    driver.get(url)
    driver.find_element_by_xpath("//a[@trace='srp_bottom_pagedown']").click()
    time.sleep(4)
    driver.get(driver.current_url)
    get_info(driver.current_url, page)      # driver.current_url可以获取当前页面的url


if __name__ == "__main__":
    page = 1
    driver.get("https://www.taobao.com")
    driver.implicitly_wait(10)      # 隐式等待10秒
    driver.find_element_by_id("q").clear()  # 清除id为q 输入框里面的内容
    driver.find_element_by_id("q").send_keys("小米8")    # 给输入框一个值
    driver.find_element_by_class_name("btn-search").click()     # 点击对应条件的标签
    get_info(driver.current_url, page)      # 给get_info函数当前页面URL和page

基本的注释也都有,唯一的改动就是只在主函数的入口写了一个隐式等待,其他的地方没有写,因为无意中好像看到有博客说瘾式等待只需要写一次就可以了,暂时没有验证,后续再看看吧

猜你喜欢

转载自blog.csdn.net/rongDang/article/details/81330869