def download_book(url, name):
chromedriver = '/home/rajdeep1008/Desktop/chromedriver'
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get(url)
link = driver.find_element_by_link_text(name)
actionChains = ActionChains(driver)
actionChains.context_click(link)
actionChains.send_keys(Keys.ARROW_DOWN)
actionChains.send_keys(Keys.ARROW_DOWN)
actionChains.send_keys(Keys.ARROW_DOWN)
actionChains.send_keys(Keys.ARROW_DOWN)
actionChains.send_keys(Keys.RETURN)
actionChains.perform()
while True:
if not os.path.isfile('/home/rajdeep1008/Downloads/' + name + '.pdf'):
time.sleep(5)
else:
break
driver.quit()
# download_book('http://it-ebooks.info/book/6719/', 'Android Studio Game Development')
python类ActionChains()的实例源码
def move_to(self, selector, click=False):
'''
Move to the element matched by selector or passed as argument.
Parameters
----------
selector: str
Any valid CSS selector
click: bool
Whether or not to click the element after hovering
defaults to False
'''
try:
elem = self.get_element(selector)
action = webdriver.ActionChains(self.browser)
action.move_to_element(elem)
if click:
action.click(elem)
action.perform()
except WebDriverException:
print("move_to isn't supported with this browser driver.")
def drag_and_drop(self, from_selector, to_selector):
'''
Drags an element into another.
Parameters
----------
from_selector: str
A CSS selector to search for. This can be any valid CSS selector.
Element to be dragged.
to_selector: str
A CSS selector to search for. This can be any valid CSS selector.
Target element to be dragged into.
'''
from_element = self.get_element(from_selector)
to_element = self.get_element(to_selector)
ActionChains(self.browser).drag_and_drop(from_element, to_element).perform()
def _drag_and_drop(self, source, **kwargs):
"""Send values to a particular element,
simulates typing into a element
:Arguments:
1. source = a valid WebElement
2. target = a valid WebElement
"""
status = True
print_info("Simulate a drag and drop")
try:
browser_instance = kwargs.get('browser')
target = self._get_element(browser_instance,
kwargs.get('target_locator'))
if source is not None and target is not None:
ActionChains(browser_instance).drag_and_drop(source,
target).perform()
except Exception as e:
print_error("An Exception Occurred {}".format(e))
status = False
return status
def click(self, element=None):
if element is None:
element = self.element
click_element = ActionChains(self.browser).click_and_hold(element).release(element)
click_element.perform()
def move_slider(self, slider, offset=0.0):
"""Click somewhere in an horizontal slider. The position is given in fraction
of its width: *offset* from 0 to 1."""
width = slider.size['width']
action_chains = ActionChains(self.driver)
# Move to the middle of the slider (default), then to its leftmost point
action_chains.move_to_element(slider).move_by_offset(-width/2.0, 0)
# Double-click twice to know where the cursor is.
#action_chains.context_click().context_click()
# Need to perform() because it seems to bug with move_by_offset otherwise
action_chains.perform()
# Offset to the right
action_chains.move_by_offset(width * offset, 0)
# Double-click twice to know where the cursor is
#action_chains.context_click().context_click()
action_chains.click().perform()
def click(self, element):
actions = webdriver.ActionChains(self.driver)
actions.move_to_element(element)
actions.click(element)
actions.perform()
def test_08_wrong_account(self, base_url, selenium):
self.baseurl = base_url
self.get(selenium, base_url + '/reconcile')
src = selenium.find_element_by_id('ofx-1-OFXT4')
tgt = selenium.find_element_by_id(
'trans-4').find_element_by_class_name('reconcile-drop-target')
# get the innerHTML of both columns
trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML')
ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML')
# drag and drop
chain = ActionChains(selenium)
chain.drag_and_drop(src, tgt).perform()
# sleep a bit for the drag to stop
sleep(1)
# ensure both columns are still the same
assert selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML') == trans_div
assert selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML') == ofxtrans_div
# ensure reconciled JS var is still the same
assert self.get_reconciled(selenium) == {}
def test_09_wrong_amount(self, base_url, selenium):
self.baseurl = base_url
self.get(selenium, base_url + '/reconcile')
src = selenium.find_element_by_id('ofx-1-OFXT4')
tgt = selenium.find_element_by_id(
'trans-1').find_element_by_class_name('reconcile-drop-target')
# get the innerHTML of both columns
trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML')
ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML')
# drag and drop
chain = ActionChains(selenium)
chain.drag_and_drop(src, tgt).perform()
# sleep a bit for the drag to stop
sleep(1)
# ensure both columns are still the same
assert selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML') == trans_div
assert selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML') == ofxtrans_div
# ensure reconciled JS var is still the same
assert self.get_reconciled(selenium) == {}
def test_10_wrong_acct_and_amount(self, base_url, selenium):
self.baseurl = base_url
self.get(selenium, base_url + '/reconcile')
src = selenium.find_element_by_id('ofx-1-OFXT4')
tgt = selenium.find_element_by_id(
'trans-3').find_element_by_class_name('reconcile-drop-target')
# get the innerHTML of both columns
trans_div = selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML')
ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML')
# drag and drop
chain = ActionChains(selenium)
chain.drag_and_drop(src, tgt).perform()
# sleep a bit for the drag to stop
sleep(1)
# ensure both columns are still the same
assert selenium.find_element_by_id('trans-panel').get_attribute(
'innerHTML') == trans_div
assert selenium.find_element_by_id('ofx-panel').get_attribute(
'innerHTML') == ofxtrans_div
# ensure reconciled JS var is still the same
assert self.get_reconciled(selenium) == {}
def check_auth_block(self):
block = self.is_element_visible(LoginPageLocators.AUTH_BLOCK)
if block:
print("???????")
actions = ActionChains()
# actions.click_and_hold(block)
# actions.move_by_offset(298, 0)
actions.drag_and_drop_by_offset(self.findElement(LoginPageLocators.AUTH_BLOCK), 298, 0)
actions.perform()
time.sleep(2)
flag = 1 if '????' in self.page_source() else 0
return flag
else:
print("????????????")
flag = 1
return flag
def check_block(self):
time.sleep(5)
block = self.is_element_visible(CheckinPageLocators.BLOCK)
if block:
print("???????")
actions = ActionChains()
# actions.click_and_hold(block)
# actions.move_by_offset(258, 0)
actions.drag_and_drop_by_offset(block, 258, 0)
actions.perform()
time.sleep(2)
flag = 1 if '????' in self.page_source() else 0
return flag
else:
print("????????????")
flag = 1
return flag
def bot_mitigation(self):
"""Three commands for bot-detection mitigation when getting a site."""
# bot mitigation 1: move the randomly around a number of times
window_size = self.webdriver.get_window_size()
num_moves = 0
num_fails = 0
while num_moves < NUM_MOUSE_MOVES + 1 and num_fails < NUM_MOUSE_MOVES:
try:
if num_moves == 0: # move to the center of the screen
x = int(round(window_size['height']/2))
y = int(round(window_size['width']/2))
else: # move a random amount in some direction
move_max = random.randint(0, 500)
x = random.randint(-move_max, move_max)
y = random.randint(-move_max, move_max)
action = ActionChains(self.webdriver)
action.move_by_offset(x, y)
action.perform()
num_moves += 1
except MoveTargetOutOfBoundsException:
num_fails += 1
self.log.warning("Mouse movement out of bounds,"
"trying a different offset...")
# bot mitigation 2: scroll in random intervals down page
scroll_down(self.webdriver)
# mitigation 3: randomly wait so that page visits appear irregularly
time.sleep(random.randrange(RANDOM_SLEEP_LOW, RANDOM_SLEEP_HIGH))
def reboot_verify_code(self):
time.sleep(3)
url = "https://ssl.captcha.qq.com/cap_union_new_show?aid=549000929&captype=&protocol=https&clientype=1&disturblevel=&apptype=2&noheader=0&color=&showtype=&fb=1&theme=&lang=2052&sess=BNMDwCNY6DHgvp19N75V1T62mdLntiP-PmMrPsSDfhljYM3PbvQa2YmZAiRB5yNaTGAJmEgshmGdugfAHEFElzFJsj25whcKd4PAMeNWF2tFbbPmPSMJ-zwovyzlm4D_WeopGav24sgESs1e47uDuSMicJPnaDpkbs3QCquiF2BmVEfgz-nW19mJEIEHdJxYn1XQd-wkyCU*&fwidth=0&uid=1473018671&cap_cd=-2wDJk7I9ogP7glTeXWzGfZ9pzEC6vuCa9cSAkbUMizVwgdtBrq8xA**&rnd=339939"
# BS = BeautifulSoup(url,'lxml')
# Bfind = BS.find('iframe')['src']
# self.browser.get(Bfind)
self.browser.get(url)
cap_input = self.browser.find_element_by_xpath('//*[@id="cap_input"]')
cap_que_img = self.browser.find_element_by_xpath('//*[@id="cap_que_img"]')
verify_btn = self.browser.find_element_by_xpath('//*[@id="verify_btn"]')
self.dowload_verify_code_img(cap_que_img)
verify_code_input = input("???: ")
action_code = ActionChains(self.browser)
cap_input.clear()
action_code.move_to_element(cap_input).click().send_keys(verify_code_input)
action_code.move_to_element(verify_btn).click()
action_code.perform()
def DoubleClick(cls):
log.step_normal("Element [%s]: Do DoubleClick()" % cls.__name__)
# cls.__wait()
WebDriverWait(env.driver, 10).until(lambda the_driver:
the_driver.find_element(cls.by, cls.value).is_displayed())
elements = env.driver.find_elements(cls.by, cls.value)
action = webdriver.ActionChains(env.driver)
action.double_click(elements[cls.index])
action.perform()
time.sleep(3)
env.driver.switch_to_window(env.driver.window_handles[-1])
# env.driver.maximize_window()
time.sleep(3)
cls.__clearup()
def TypeIn(cls, value):
"""
input value without clear existed values
"""
if value == "":
return
log.step_normal(u"Element [%s]: TypeIn Value [%s]." % (cls.__name__, value))
# cls.__wait()
WebDriverWait(env.driver, 10).until(lambda the_driver:
the_driver.find_element(cls.by, cls.value).is_displayed())
elements = env.driver.find_elements(cls.by, cls.value)
action = webdriver.ActionChains(env.driver)
action.send_keys_to_element(elements[cls.index], value)
action.perform()
cls.__clearup()
def Set(cls, value):
log.step_normal("Element [%s]: Set [%s]." % (cls.__name__, value))
if isNumberType(value):
value = str(value)
cls.__wait()
elements = env.threadlocal.BROWSER.find_elements(cls.by, cls.value)
if elements[cls.index].tag_name == "select" or elements[cls.index].tag_name == "ul":
cls.Select(value)
else:
elements[cls.index].clear()
action = webdriver.ActionChains(env.threadlocal.BROWSER)
action.send_keys_to_element(elements[cls.index], value) #????????
action.perform()
cls.__clearup()
def Click(cls):
log.step_normal("Element [%s]: Click()" % (cls.__name__))
cls.__wait()
elements = env.threadlocal.BROWSER.find_elements(cls.by, cls.value)
action = webdriver.ActionChains(env.threadlocal.BROWSER)
action.click(elements[cls.index])
action.perform()
#=======================================================================
# action = webdriver.ActionChains(env.threadlocal.BROWSER)
# action.key_up(Keys.CONTROL, elements[cls.index])
# action.perform()
#
# action.click(elements[cls.index])
# action.perform()
#=======================================================================
cls.__clearup()
def _goto_next_page(self):
"""
Click the next page element,
Returns:
The url of the next page or False if there is no such url
(end of available pages for instance).
"""
next_url = ''
element = self._find_next_page_element()
if hasattr(element, 'click'):
next_url = element.get_attribute('href')
try:
element.click()
except WebDriverException:
# See http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error
# first move mouse to the next element, some times the element is not visibility
selector = self.next_page_selectors[self.search_engine_name]
if selector:
try:
next_element = WebDriverWait(self.webdriver, 5).until(
EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
webdriver.ActionChains(self.webdriver).move_to_element(next_element).perform()
# wait until the next page link emerges
WebDriverWait(self.webdriver, 8).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
element = self.webdriver.find_element_by_css_selector(selector)
next_url = element.get_attribute('href')
element.click()
except WebDriverException:
pass
# wait until the next page was loaded
if not next_url:
return False
else:
return next_url
def _mouse_over(self, element, **kwargs ):
"""Moving the mouse to the middle of an element """
status = False
print_info("mouse over operation")
browser_instance = kwargs.get('browser')
if element is not None:
ActionChains(browser_instance).move_to_element(element).perform()
status = True
return status
def _double_click_element(self, element, **kwargs):
""" Double clicks on the provided element
:Arguments:
1. element = a valid WebElement
"""
status = True
print_info("Double click on element")
try:
browser_instance = kwargs.get('browser')
ActionChains(browser_instance).double_click(element)
except Exception as e:
print_error("An Exception Occurred {}".format(e))
status = False
return status
def _perform_keypress(self, element, **kwargs):
"""
This function expects to receive a browser instance through the
"browser" argument and a key "keys" through the kwargs.
The value for "keys" would be a list of keys tha need to pressed.
"""
status = True
flag = False
keys = kwargs.get('keys')
actions = ActionChains(element)
for key in keys:
try:
selenium_key = KEYS[key.upper()]
except KeyError:
print_error("{0} is not supported by Selenium.".format(key))
status = False
else:
flag = True
actions.send_keys(selenium_key)
if flag:
actions.perform()
sleep(2)
return status
def test_1_view_alignment(self):
actions = ActionChains(self.driver)
rows = self.waitForAll('.public_fixedDataTable_bodyRow .public_fixedDataTableCell_cellContent')
actions.double_click(rows[0]).perform()
self.waitFor('.igv-modal', 3)
def robust_click(self, elt):
"""Click on the element, for the click() method is bugged half of the time"""
self.driver.execute_script("arguments[0].scrollIntoView(true);", elt)
action = ActionChains(self.driver)
action.move_to_element(elt).click().perform()
def moveToElement(self, element):
self.driver.execute_script("return arguments[0].scrollIntoView();", element)
actions = webdriver.ActionChains(self.driver)
actions.move_to_element(element)
actions.perform()
def login(self, username, password):
self.driver.get(url)
elem_username = self.driver.find_element_by_name('username')
elem_username.send_keys(username)
elem_password = self.driver.find_element_by_name('password')
elem_password.send_keys(password)
# # ????
# action_chains = ActionChains(self.driver)
# # elem_code = self.driver.find_element_by_name('geetest_validate')
# elem_code = self.driver.find_element_by_class_name('gt_slider_knob')
# location = elem_code.location
# size = elem_code.size
# moveX = 99 # ????
# action_chains.click_and_hold(elem_code)
# time.sleep(5)
# action_chains.drag_and_drop_by_offset(elem_code, moveX, 0).perform()
# # action_chains.move_to_element_with_offset(elem_code, moveX, 0).perform()
# elem_login = self.driver.find_element_by_class_name("loginbox-sbt btn-sub")
# elem_login.submit()
try:
somedom = WebDriverWait(self.driver, 30)
html = somedom.find_element_by_xpath("//div[@class='o-login fl']")
print(html)
finally:
print("finally")
pass
self.driver.quit()
# driver.quit()
def mouse_hover(self):
"""Hover the mouse over element
:return: None
"""
webdriver.ActionChains(self.browser).move_to_element(self.element).perform()
def check_elements_are_visible(driver: webdriver, elements: list):
take_screenshot(driver, NAME)
for element in elements:
selector = SCOPE_ELEMENTS[element.lower()]
with selenium_action(
driver, "Could not find '%s' on '%s' using '%s' selector",
element, driver.current_url, selector):
page_element = driver.find_element_by_css_selector(selector)
if "firefox" not in driver.capabilities["browserName"].lower():
logging.debug("Moving focus to '%s' element", element)
action_chains = ActionChains(driver)
action_chains.move_to_element(page_element)
action_chains.perform()
with assertion_msg("Expected to see '%s' but can't see it", element):
assert page_element.is_displayed()
def check_elements_are_visible(driver: webdriver, elements: list):
take_screenshot(driver, NAME)
for element in elements:
selector = SCOPE_ELEMENTS[element.lower()]
with selenium_action(
driver, "Could not find '%s' on '%s' using '%s' selector",
element, driver.current_url, selector):
page_element = driver.find_element_by_css_selector(selector)
if "firefox" not in driver.capabilities["browserName"].lower():
logging.debug("Moving focus to '%s' element", element)
action_chains = ActionChains(driver)
action_chains.move_to_element(page_element)
action_chains.perform()
with assertion_msg("Expected to see '%s' but can't see it", element):
assert page_element.is_displayed()
def check_elements_are_visible(driver: webdriver, elements: list):
take_screenshot(driver, NAME)
for element in elements:
selector = SCOPE_ELEMENTS[element.lower()]
with selenium_action(
driver, "Could not find '%s' on '%s' using '%s' selector",
element, driver.current_url, selector):
page_element = driver.find_element_by_css_selector(selector)
if "firefox" not in driver.capabilities["browserName"].lower():
logging.debug("Moving focus to '%s' element", element)
action_chains = ActionChains(driver)
action_chains.move_to_element(page_element)
action_chains.perform()
with assertion_msg("Expected to see '%s' but can't see it", element):
assert page_element.is_displayed()