首页 > 解决方案 > 如何更改 Apache 权限?

问题描述

我需要网络抓取(例如www.google.com)并在另一个网页中显示结果,但它接缝 apache 的用户无权打开 firefox 来抓取

该项目有一个docker映像(php-apache)、一个 php 文件(调用抓取)和一个使用 selenium 抓取的 python 文件。

我可以在 php 中执行一个通用的 python 脚本,如果我以 root 身份访问 Docker 容器,我可以成功运行我的 python抓取文件。但是,当 php 文件以 www-data 用户身份调用 python scrape文件时,无法打开 selenium 驱动程序。

如何将 apache 用户更改为 root 或如何允许 www-data 用户运行 firefox?

Dockerfile

FROM php:7.4.15-apache

# Change apache permissions
RUN usermod -u 1000 www-data
RUN groupmod -g 1000 www-data

# Upgrade installed packages
RUN apt update

# Install python
RUN apt install -y python3.7
# Register the version in alternatives
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1
# Set python3 as the default python
RUN update-alternatives --set python /usr/bin/python3.7

# Install pip
RUN apt install -y python3-pip
# Set pip3 as the default pip
RUN update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1

# Install python modules
RUN pip install selenium

# Install Firefox
RUN apt install -y firefox-esr

# Copy geckodriver from host to docker
COPY geckodriver /usr/local/bin/

码头工人-compose.yml

version: '3'

services:
  php:
    build: ./docker-images/php-apache/
    container_name: test_scraping_php-container
    ports:
      - "8080:80"
    volumes:
      - ./www:/var/www/html

索引.php

<html>
    <head>
        <title>Test PHP - Python - Scraping</title>
    </head>
    <body>
        <?php 
            $cmd = 'python user.py';
            $result = shell_exec($cmd);
            echo "<p>Python get user: $result </p>"; 
        ?>
        <?php 
            $cmd = 'python scraping.py';
            $result = shell_exec($cmd);
            echo "<p>Python get title (scraping): $result </p>";
        ?>
    </body>
</html>

用户.py

import getpass

print(getpass.getuser())

抓取.py

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

url = 'https://www.google.com'
options = Options()
options.headless = True
try:
    driver = webdriver.Firefox(options=options)
    driver.get(url)
    print(driver.title)
except:
    print('Error!')

标签: pythonphpdockerapacheselenium

解决方案


推荐阅读