如何在共享主机Cpanel终端运行Selenium Python爬虫脚本
共享主机Cpanel运行Selenium Python脚本操作指引
前置检查
- 先确认你的共享主机支持SSH访问,且没有限制运行二进制程序、后台进程:部分廉价共享主机会禁用Chrome这类资源占用较高的程序,若存在限制需先联系主机商开通权限
- 确认主机已经安装Python 3.7+版本,可在Cpanel终端执行
python3 --version查看版本号 - 如果你的Cpanel提供Python Selector功能,优先在面板里配置对应版本的Python虚拟环境,再在虚拟环境中安装依赖运行脚本,避免权限问题
安装Python依赖包
在Cpanel终端进入你脚本存放的目录,执行以下命令安装依赖:
pip3 install requests selenium webdriver-manager beautifulsoup4 lxml
如果没有权限全局安装,加--user参数:
pip3 install --user requests selenium webdriver-manager beautifulsoup4 lxml
适配Linux环境修改原有脚本
共享主机多为Linux系统,原有Windows下的脚本需要补充Linux无头Chrome必加启动参数,同时适配Selenium 4+的语法规范,修改后的参考脚本如下:
import requests import io import time from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options() options.headless = True options.add_argument("user-agent=Chrome/80.0.3987.132") # 新增Linux环境必加参数,避免Chrome启动失败 options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-gpu") options.add_argument("--disable-extensions") # 如果后续自动安装驱动失败,手动安装Chrome和ChromeDriver后替换下面两行路径即可 # options.binary_location = "/home/你的Cpanel用户名/自定义目录/chrome" # driver = webdriver.Chrome(service=Service(executable_path="/home/你的Cpanel用户名/自定义目录/chromedriver"), options=options) # 默认用自动安装驱动逻辑 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) with open("links.txt", "r", encoding = "utf-8") as a_file: for line in a_file: stripped_line = line.strip() driver.get(stripped_line) file1=open('data.txt','a') time.sleep(15) html_source=driver.page_source soup=BeautifulSoup(html_source,'lxml') # 匹配目标元素 images=soup.find_all('div',attrs={'class':'style-module--action--1Avvt'}) for image in images: file1.write(str(image.findAll('a'))) file1.write('\n') file1.close() driver.quit()
运行脚本
- 前台运行直接执行命令:
python3 你的脚本文件名.py
- 如需后台长期运行,避免SSH断开后脚本停止,用nohup命令启动:
nohup python3 你的脚本文件名.py &
运行日志会自动保存在同目录的nohup.out文件中,可随时查看运行状态。
常见问题排查
- Chrome启动失败:优先确认已经添加上述
--no-sandbox等参数,还是启动失败的话手动下载Linux静态编译版Chrome和对应版本ChromeDriver,解压后添加可执行权限,再在脚本中手动指定路径即可 - 运行中途进程被终止:说明共享主机资源不足,可适当调长
time.sleep的等待时长,降低爬取频率减少资源占用 - 文件读写报错:给脚本所在目录设置755权限,保证脚本有读取
links.txt、写入data.txt的权限
内容的提问来源于stack exchange,提问作者Katherine Elizabeth Kath
相关产品推荐
相关产品推荐

