创建使用代理的无头浏览器
from selenium import webdriver
from selenium.common import exceptions
class Driver:
def __init__(self):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--proxy-server=http://{ip}:{port}'.format(ip=ip, port=port))
self.driver = webdriver.Chrome(executable_path=Chrome_path, chrome_options=chrome_options)
x_size = 1200
y_size = 900
self.driver.set_window_size(x_size, y_size)
self.size = self.driver.get_window_size()
def get(self, url):
self.driver.get(url)
def find_element_by_xpath(self, xpath):
return self.driver.find_element_by_xpath(xpath)
def __del__(self):
self.driver.quit()
截某元素的图
from PIL import Image
def get_element_pic(element, driver, pic_name='screenshot.png'):
driver.save_screenshot('screenshot.png')
left = element.location['x']
top = element.location['y']
right = element.location['x'] + element.size['width']
bottom = element.location['y'] + element.size['height']
im = Image.open('screenshot.png')
im = im.crop((left, top, right, bottom))
im.save(pic_name)
常用鼠标操作
element.click()
element.put_keys(string)
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
action.move_to_element(element).perform()
action.click_and_hold(element).perform()
action.release(element).perform()
action.move_by_offset(x, y).perform()