python - 如何使用selenium让chrome浏览器在后台运行

标签 python selenium selenium-webdriver selenium-chromedriver webautomation

我正在尝试使用 pyautogui 自动执行 WhatsApp 批量发送消息。我能够发送它们,但每条消息都会弹出一个新选项卡,我的工作会受到干扰。如何让 WhatsApp 网页选项卡在后台或其他窗口中运行而不影响我的工作?这是我的代码。我收到错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-3555dd798e71> in <module>
     10 chrome_options.add_argument("--headless")
     11 
---> 12 driver = webdriver.Chrome(executable_path=r"C:/Users/AB/chromedriver", chrome_options=Options)
     13 
     14 data = pd.read_excel("C:/Users/AB/Desktop/contacts2.xlsx")

C:\anaconda\lib\site-packages\selenium\webdriver\chrome\webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive) 62         else:
     63             if desired_capabilities is None:
---> 64                 desired_capabilities = options.to_capabilities()
     65             else:
     66                 desired_capabilities.update(options.to_capabilities())

**TypeError: to_capabilities() missing 1 required positional argument: 'self'**

这是更新后的代码:

import pyautogui as pg
#import webbrowser as web
import time
import pandas as pd
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Chrome(executable_path=r"C:/Users/AB/chromedriver", chrome_options=Options)

data = pd.read_excel("C:/Users/AB/Desktop/contacts2.xlsx")
data_dict = data.to_dict('list')
leads = data_dict['contact']
messages = data_dict['msg']
combo = zip(leads,messages)
first = True
for lead,message in combo:
    time.sleep(6)
    driver.get("https://web.whatsapp.com/send?phone="+lead+"&text="+message)
    if first:
        time.sleep(8)
        first=False
    width,height = pg.size()
    pg.click(width/2,height/2)
    time.sleep(8)
    pg.press('enter')
    time.sleep(8)
    pg.hotkey('ctrl', 'w')```

最佳答案

要运行 chrome-headless 只需在 chrome_options.add_argument 中添加 --headless,即:

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

chrome_options = Options()
chrome_options.add_argument("--headless")

在这种情况下,您将看不到 chrom 窗口。

关于python - 如何使用selenium让chrome浏览器在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65989214/

相关文章:

python - SQLAlchemy - 访问反射表的别名列时出现 NoReferencedTableError 异常

python - 单击“'' 现在不行”在 Instagram 通知上询问使用 Selenium 和 Python

c# - Selenium 为什么将 acceptuntrustedcertificates 设置为 true 对于 firefox 驱动程序不起作用?

python - 如何从 Selenium 浏览器加载 session 和 cookie 到 Python 中的请求库?

json - 从网站的 GET 请求中获取 queryString - 替代工具然后是 Selenium

python - 使用 AzureMachineLearningFileSystem 更新时出现 NotImplementedError

python - 拆分 Django 项目

python - 为什么 PyTorch nn.Module.cuda() 不移动模块张量而只移动参数和缓冲区到 GPU?

java - FluentWait 类型中的直到(Function<? super WebDriver,V>) 方法不适用于参数 (boolean, ExpectedCondition<WebElement>)

ruby-on-rails - 使用 Capybara/Selenium 测试 html5 文件上传?