【问题标题】:How to make the chrome browser run in background using selenium如何使用 selenium 使 chrome 浏览器在后台运行
【发布时间】:2021-05-05 10:09:59
【问题描述】:

我正在尝试自动化我的 WhatsApp 以使用 pyautogui 批量发送消息。我能够发送它们,但是对于每条消息,都会弹出一个新标签,并且我的工作会受到干扰。如何让 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')```

【问题讨论】:

  • 以无头模式运行?
  • 谢谢,我在无头模式下使用时重现了上述错误

标签: python selenium selenium-webdriver selenium-chromedriver webautomation


【解决方案1】:

要运行 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 窗口。

【讨论】:

  • 非常感谢,但是,在添加代码并指定 chromedriver 路径后,我收到错误“TypeError: to_capabilities() missing 1 required positional argument: 'self'。
  • 你可以发布一些其他链接,因为我无法从发布的内容中弄清楚
猜你喜欢
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
相关资源
最近更新 更多