如何在 Databricks 中使用 Selenium 以及访问和移动下载的文件到安装的存储并保持 Chrome 和 Chrome 驱动程序版本同步?
How to use Selenium in Databricks and accessing and moving downloaded files to mounted storage and keep Chrome and ChromeDriver versions in sync?
我看过一些关于使用 %sh
安装 Chrome 驱动程序和 Chrome 在 Databricks 中使用 Selenium 的帖子。这对我来说很好,但是当我需要下载文件时遇到了很多麻烦。该文件会下载,但我无法在数据块的文件系统中找到它。即使我在实例化 Chrome 到 Azure Blob 存储上的已安装文件夹时更改了下载路径,下载后文件也不会放置在那里。在不手动更改版本号的情况下,保持 Chrome 浏览器和 Chrome 驱动程序版本自动同步也是一个问题。
以下链接显示有同样问题但没有明确答案的人:
https://forums.databricks.com/questions/19376/if-my-notebook-downloads-a-file-from-a-website-by.html
Is there a way to identify where the file gets downloaded in Azure Databricks when I do web automation using Selenium Python?
还有一些人在努力让 Selenium 正确地 运行:
https://forums.databricks.com/questions/14814/selenium-in-databricks.html
不在路径错误:
https://webcache.googleusercontent.com/search?q=cache:NrvVKo4LLdIJ:
是否有关于在 Databricks 上使用 Selenium 和管理下载文件的明确指南?我怎样才能使 Chrome 浏览器和 Chrome 驱动程序版本自动同步?
这是安装 Selenium、Chrome 和 Chrome 驱动程序的指南。这也会在通过 Selenium 下载后将文件移动到您安装的存储中。每个数字都应该在它自己的单元格中。
- 安装硒
%pip install selenium
- 做你的进口
import pickle as pkl
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
- 将最新的 Chrome 驱动程序下载到 DBFS 根存储
/tmp/
。 curl 命令将获取最新的 Chrome 版本并存储在 version
变量中。注意 $
. 之前的转义符 \
%sh
version=`curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE`
wget -N https://chromedriver.storage.googleapis.com/${version}/chromedriver_linux64.zip -O /tmp/chromedriver_linux64.zip
- 将文件解压缩到 DBFS 根目录中的一个新文件夹
/tmp/
。我尝试使用非根路径,但它不起作用。
%sh
unzip /tmp/chromedriver_linux64.zip -d /tmp/chromedriver/
- 获取最新的 Chrome 下载并安装它。
%sh
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
** 步骤 3 - 5 可以合并为一个命令。您还可以使用以下内容创建一个 shell 脚本并将其用作初始化文件来为您的集群进行配置,这在使用使用瞬态集群的作业集群时特别有用,因为初始化脚本适用于所有工作节点,而不仅仅是驱动程序节点。这也会安装 Selenium,让您可以跳过第 1 步。只需在新笔记本中粘贴一个单元格 运行,然后将您的初始化脚本指向 dbfs:/init/init_selenium.sh
。现在每次集群或临时集群启动时,都会在您的作业开始 运行.
之前在所有工作节点上安装 Chrome、ChromeDriver 和 Selenium
%sh
# dbfs:/init/init_selenium.sh
cat > /dbfs/init/init_selenium.sh <<EOF
#!/bin/sh
echo Install Chrome and Chrome driver
version=`curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE`
wget -N https://chromedriver.storage.googleapis.com/${version}/chromedriver_linux64.zip -O /tmp/chromedriver_linux64.zip
unzip /tmp/chromedriver_linux64.zip -d /tmp/chromedriver/
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
pip install selenium
EOF
cat /dbfs/init/init_selenium.sh
- 配置您的存储帐户。示例是使用 ADLSGen2 的 Azure Blob 存储。
service_principal_id = "YOUR_SP_ID"
service_principle_key = "YOUR_SP_KEY"
tenant_id = "YOUR_TENANT_ID"
directory = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/token"
configs = {"fs.azure.account.auth.type": "OAuth",
"fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
"fs.azure.account.oauth2.client.id": service_principal_id,
"fs.azure.account.oauth2.client.secret": service_principle_key,
"fs.azure.account.oauth2.client.endpoint": directory,
"fs.azure.createRemoteFileSystemDuringInitialization": "true"}
- 配置安装位置和安装。
mount_point = "/mnt/container-data/"
mount_point_main = "/dbfs/mnt/container-data/"
container = "container-data"
storage_account = "adlsgen2"
storage = "abfss://"+ container +"@"+ storage_account + ".dfs.core.windows.net"
utils_folder = mount_point + "utils/selenium/"
raw_folder = mount_point + "raw/"
if not any(mount_point in mount_info for mount_info in dbutils.fs.mounts()):
dbutils.fs.mount(
source = storage,
mount_point = mount_point,
extra_configs = configs)
print(mount_point + " has been mounted.")
else:
print(mount_point + " was already mounted.")
print(f"Utils folder: {utils_folder}")
print(f"Raw folder: {raw_folder}")
- 创建实例化 Chrome 浏览器的方法。我需要载入我放在
utils
文件夹中的 cookie 文件,该文件夹指向 mnt/container-data/utils/selenium
。确保参数相同(无沙盒、无头、disable-dev-shm-usage)
def init_chrome_browser(download_path, chrome_driver_path, cookies_path, url):
"""
Instatiates a Chrome browser.
Parameters
----------
download_path : str
The download path to place files downloaded from this browser session.
chrome_driver_path : str
The path of the chrome driver executable binary (.exe file).
cookies_path : str
The path of the cookie file to load in (.pkl file).
url : str
The URL address of the page to initially load.
Returns
-------
Browser
Returns the instantiated browser object.
"""
options = Options()
prefs = {'download.default_directory' : download_path}
options.add_experimental_option('prefs', prefs)
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--start-maximized')
options.add_argument('window-size=2560,1440')
print(f"{datetime.now()} Launching Chrome...")
browser = webdriver.Chrome(service=Service(chrome_driver_path), options=options)
print(f"{datetime.now()} Chrome launched.")
browser.get(url)
print(f"{datetime.now()} Loading cookies...")
cookies = pkl.load(open(cookies_path, "rb"))
for cookie in cookies:
browser.add_cookie(cookie)
browser.get(url)
print(f"{datetime.now()} Cookies loaded.")
print(f"{datetime.now()} Browser ready to use.")
return browser
- 实例化浏览器。将下载位置设置为 DBFS 根文件系统
/tmp/downloads
。确保 cookies 路径前面有 /dbfs
,这样完整的 cookies 路径就像 /dbfs/mnt/...
browser = init_chrome_browser(
download_path="/tmp/downloads",
chrome_driver_path="/tmp/chromedriver/chromedriver",
cookies_path="/dbfs"+ utils_folder + "cookies.pkl",
url="YOUR_URL"
)
进行导航和所需的任何下载。
可选:检查您的下载位置。在此示例中,我下载了一个 CSV 文件,并将搜索下载的文件夹,直到找到该文件格式。
import os
import os.path
for root, directories, filenames in os.walk('/tmp'):
print(root)
if any(".csv" in s for s in filenames):
print(filenames)
break
- 将文件从 DBFS root tmp 复制到您安装的存储 (
/mnt/container-data/raw/
)。您也可以在此操作期间重命名。使用 dbutils 时只能使用 file:
前缀访问根文件系统。
dbutils.fs.cp("file:/tmp/downloads/file1.csv", f"{raw_folder}file2.csv')
我看过一些关于使用 %sh
安装 Chrome 驱动程序和 Chrome 在 Databricks 中使用 Selenium 的帖子。这对我来说很好,但是当我需要下载文件时遇到了很多麻烦。该文件会下载,但我无法在数据块的文件系统中找到它。即使我在实例化 Chrome 到 Azure Blob 存储上的已安装文件夹时更改了下载路径,下载后文件也不会放置在那里。在不手动更改版本号的情况下,保持 Chrome 浏览器和 Chrome 驱动程序版本自动同步也是一个问题。
以下链接显示有同样问题但没有明确答案的人:
https://forums.databricks.com/questions/19376/if-my-notebook-downloads-a-file-from-a-website-by.html
Is there a way to identify where the file gets downloaded in Azure Databricks when I do web automation using Selenium Python?
还有一些人在努力让 Selenium 正确地 运行: https://forums.databricks.com/questions/14814/selenium-in-databricks.html
不在路径错误: https://webcache.googleusercontent.com/search?q=cache:NrvVKo4LLdIJ:
是否有关于在 Databricks 上使用 Selenium 和管理下载文件的明确指南?我怎样才能使 Chrome 浏览器和 Chrome 驱动程序版本自动同步?
这是安装 Selenium、Chrome 和 Chrome 驱动程序的指南。这也会在通过 Selenium 下载后将文件移动到您安装的存储中。每个数字都应该在它自己的单元格中。
- 安装硒
%pip install selenium
- 做你的进口
import pickle as pkl
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
- 将最新的 Chrome 驱动程序下载到 DBFS 根存储
/tmp/
。 curl 命令将获取最新的 Chrome 版本并存储在version
变量中。注意$
. 之前的转义符
\
%sh
version=`curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE`
wget -N https://chromedriver.storage.googleapis.com/${version}/chromedriver_linux64.zip -O /tmp/chromedriver_linux64.zip
- 将文件解压缩到 DBFS 根目录中的一个新文件夹
/tmp/
。我尝试使用非根路径,但它不起作用。
%sh
unzip /tmp/chromedriver_linux64.zip -d /tmp/chromedriver/
- 获取最新的 Chrome 下载并安装它。
%sh
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
** 步骤 3 - 5 可以合并为一个命令。您还可以使用以下内容创建一个 shell 脚本并将其用作初始化文件来为您的集群进行配置,这在使用使用瞬态集群的作业集群时特别有用,因为初始化脚本适用于所有工作节点,而不仅仅是驱动程序节点。这也会安装 Selenium,让您可以跳过第 1 步。只需在新笔记本中粘贴一个单元格 运行,然后将您的初始化脚本指向 dbfs:/init/init_selenium.sh
。现在每次集群或临时集群启动时,都会在您的作业开始 运行.
%sh
# dbfs:/init/init_selenium.sh
cat > /dbfs/init/init_selenium.sh <<EOF
#!/bin/sh
echo Install Chrome and Chrome driver
version=`curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE`
wget -N https://chromedriver.storage.googleapis.com/${version}/chromedriver_linux64.zip -O /tmp/chromedriver_linux64.zip
unzip /tmp/chromedriver_linux64.zip -d /tmp/chromedriver/
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
pip install selenium
EOF
cat /dbfs/init/init_selenium.sh
- 配置您的存储帐户。示例是使用 ADLSGen2 的 Azure Blob 存储。
service_principal_id = "YOUR_SP_ID"
service_principle_key = "YOUR_SP_KEY"
tenant_id = "YOUR_TENANT_ID"
directory = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/token"
configs = {"fs.azure.account.auth.type": "OAuth",
"fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
"fs.azure.account.oauth2.client.id": service_principal_id,
"fs.azure.account.oauth2.client.secret": service_principle_key,
"fs.azure.account.oauth2.client.endpoint": directory,
"fs.azure.createRemoteFileSystemDuringInitialization": "true"}
- 配置安装位置和安装。
mount_point = "/mnt/container-data/"
mount_point_main = "/dbfs/mnt/container-data/"
container = "container-data"
storage_account = "adlsgen2"
storage = "abfss://"+ container +"@"+ storage_account + ".dfs.core.windows.net"
utils_folder = mount_point + "utils/selenium/"
raw_folder = mount_point + "raw/"
if not any(mount_point in mount_info for mount_info in dbutils.fs.mounts()):
dbutils.fs.mount(
source = storage,
mount_point = mount_point,
extra_configs = configs)
print(mount_point + " has been mounted.")
else:
print(mount_point + " was already mounted.")
print(f"Utils folder: {utils_folder}")
print(f"Raw folder: {raw_folder}")
- 创建实例化 Chrome 浏览器的方法。我需要载入我放在
utils
文件夹中的 cookie 文件,该文件夹指向mnt/container-data/utils/selenium
。确保参数相同(无沙盒、无头、disable-dev-shm-usage)
def init_chrome_browser(download_path, chrome_driver_path, cookies_path, url):
"""
Instatiates a Chrome browser.
Parameters
----------
download_path : str
The download path to place files downloaded from this browser session.
chrome_driver_path : str
The path of the chrome driver executable binary (.exe file).
cookies_path : str
The path of the cookie file to load in (.pkl file).
url : str
The URL address of the page to initially load.
Returns
-------
Browser
Returns the instantiated browser object.
"""
options = Options()
prefs = {'download.default_directory' : download_path}
options.add_experimental_option('prefs', prefs)
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--start-maximized')
options.add_argument('window-size=2560,1440')
print(f"{datetime.now()} Launching Chrome...")
browser = webdriver.Chrome(service=Service(chrome_driver_path), options=options)
print(f"{datetime.now()} Chrome launched.")
browser.get(url)
print(f"{datetime.now()} Loading cookies...")
cookies = pkl.load(open(cookies_path, "rb"))
for cookie in cookies:
browser.add_cookie(cookie)
browser.get(url)
print(f"{datetime.now()} Cookies loaded.")
print(f"{datetime.now()} Browser ready to use.")
return browser
- 实例化浏览器。将下载位置设置为 DBFS 根文件系统
/tmp/downloads
。确保 cookies 路径前面有/dbfs
,这样完整的 cookies 路径就像/dbfs/mnt/...
browser = init_chrome_browser(
download_path="/tmp/downloads",
chrome_driver_path="/tmp/chromedriver/chromedriver",
cookies_path="/dbfs"+ utils_folder + "cookies.pkl",
url="YOUR_URL"
)
进行导航和所需的任何下载。
可选:检查您的下载位置。在此示例中,我下载了一个 CSV 文件,并将搜索下载的文件夹,直到找到该文件格式。
import os
import os.path
for root, directories, filenames in os.walk('/tmp'):
print(root)
if any(".csv" in s for s in filenames):
print(filenames)
break
- 将文件从 DBFS root tmp 复制到您安装的存储 (
/mnt/container-data/raw/
)。您也可以在此操作期间重命名。使用 dbutils 时只能使用file:
前缀访问根文件系统。
dbutils.fs.cp("file:/tmp/downloads/file1.csv", f"{raw_folder}file2.csv')