下载地址:https://www.pan38.com/dow/share.php?code=JCnzE 提取密码:1133
展示一个使用Python进行基础网页自动化的示例代码,仅供学习自动化技术原理使用。
以下是使用selenium模拟网页操作的示例代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import random
class WeChatAuto:
def init(self):
self.driver_path = 'chromedriver.exe'
self.service = Service(self.driver_path)
self.options = webdriver.ChromeOptions()
self.options.add_argument('--disable-notifications')
self.driver = webdriver.Chrome(service=self.service, options=self.options)
def login_wechat(self):
self.driver.get('https://web.wechat.com/')
print('请扫描二维码登录...')
WebDriverWait(self.driver, 120).until(
EC.presence_of_element_located((By.CLASS_NAME, 'chat-list'))
)
print('登录成功!')
def send_message_to_contact(self, contact_name, message):
search_box = self.driver.find_element(By.CLASS_NAME, 'search-box')
search_box.click()
search_input = self.driver.find_element(By.CLASS_NAME, 'search-input')
search_input.send_keys(contact_name)
time.sleep(2)
contacts = self.driver.find_elements(By.CLASS_NAME, 'contact-item')
for contact in contacts:
if contact_name in contact.text:
contact.click()
break
input_box = self.driver.find_element(By.CLASS_NAME, 'input-box')
input_box.send_keys(message)
input_box.send_keys(Keys.RETURN)
print(f'消息已发送给 {contact_name}')
def send_message_to_group(self, group_name, message):
self.send_message_to_contact(group_name, message)
def auto_reply(self, keyword, reply_message):
while True:
try:
new_messages = self.driver.find_elements(By.CLASS_NAME, 'message-new')
for msg in new_messages:
if keyword in msg.text:
sender = msg.find_element(By.CLASS_NAME, 'message-sender').text
self.send_message_to_contact(sender, reply_message)
except:
pass
time.sleep(5)
def close(self):
self.driver.quit()
if name == 'main':
bot = WeChatAuto()
try:
bot.login_wechat()
bot.send_message_to_contact('测试联系人', '这是一条自动发送的消息')
time.sleep(3)
bot.send_message_to_group('测试群组', '这是群发的自动消息')
# bot.auto_reply('帮助', '这是自动回复')
finally:
bot.close()