我正在尝试使用 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/