Python selenium.webdriver.support.expected_conditions.presence_of_element_located() Examples

The following are 30 code examples of selenium.webdriver.support.expected_conditions.presence_of_element_located(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.webdriver.support.expected_conditions , or try the search function .
Example #1
Source File: eastmoney_crawler.py    From eastmoney_spider with MIT License 8 votes vote down vote up
def index_page(page):
    try:
        print('正在爬取第: %s 页' % page)
        wait.until(
            EC.presence_of_element_located((By.ID, "dt_1")))
        # 判断是否是第1页,如果大于1就输入跳转,否则等待加载完成。
        if page > 1:
            # 确定页数输入框
            input = wait.until(EC.presence_of_element_located(
                (By.XPATH, '//*[@id="PageContgopage"]')))
            input.click()
            input.clear()
            input.send_keys(page)
            submit = wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '#PageCont > a.btn_link')))
            submit.click()
            time.sleep(2)
        # 确认成功跳转到输入框中的指定页
        wait.until(EC.text_to_be_present_in_element(
            (By.CSS_SELECTOR, '#PageCont > span.at'), str(page)))
    except Exception:
        return None 
Example #2
Source File: TraTicketBooker.py    From TRA-Ticket-Booker with GNU General Public License v3.0 7 votes vote down vote up
def submit_user_data(self):
        # Submit to Authent-Number Page (press button).
        wait = WebDriverWait(self.driver, timeout=6)
        try:
            self.driver.execute_script(
                'document.getElementsByTagName("button")[0].click()'
            )
            wait.until(
                EC.presence_of_element_located(
                    (By.ID, 'idRandomPic')
                )
            )
        except:
            self.label_show_result.setText(
                '【連線逾時或是網路不穩定】\n' + 
                '【請檢查網路環境以及是否為尖峰時段。】'
            ) 
Example #3
Source File: main.py    From uncaptcha with MIT License 7 votes vote down vote up
def click_tiles(driver, coords):
    orig_srcs, new_srcs = {}, {}
    for (x, y) in coords:
        logging.debug("[*] Going to click {} {}".format(x,y))
        tile1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@id="rc-imageselect-target"]/table/tbody/tr[{0}]/td[{1}]'.format(x, y))))
        orig_srcs[(x, y)] = driver.find_element(By.XPATH, "//*[@id=\"rc-imageselect-target\"]/table/tbody/tr[{}]/td[{}]/div/div[1]/img".format(x,y)).get_attribute("src")
        new_srcs[(x, y)] = orig_srcs[(x, y)] # to check if image has changed 
        tile1.click()
        wait_between(0.1, 0.5)

    logging.debug("[*] Downloading new inbound image...")
    new_files = {}
    for (x, y) in orig_srcs:
        while new_srcs[(x, y)] == orig_srcs[(x, y)]:
            new_srcs[(x, y)] = driver.find_element(By.XPATH, "//*[@id=\"rc-imageselect-target\"]/table/tbody/tr[{}]/td[{}]/div/div[1]/img".format(x,y)).get_attribute("src")
            time.sleep(0.5)
        urllib.urlretrieve(new_srcs[(x, y)], "captcha.jpeg")
        new_path = TASK_PATH+"/new_output{}{}.jpeg".format(x, y)
        os.system("mv captcha.jpeg "+new_path)
        new_files[(x, y)] = (new_path)
    return new_files 
Example #4
Source File: upload.py    From bilibiliupload with MIT License 6 votes vote down vote up
def login(driver, filename):
        logger.info('准备更新cookie')
        # screen_shot = driver.save_screenshot('bin/1.png')
        WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, r'//*[@id="login-username"]')))
        username = driver.find_element_by_xpath(r'//*[@id="login-username"]')
        username.send_keys(engine.user_name)
        password = driver.find_element_by_xpath('//*[@id="login-passwd"]')
        password.send_keys(engine.pass_word)
        driver.find_element_by_class_name("btn-login").click()
        # logger.info('第四步')
        # try:
        cracker = slider_cracker(driver)
        cracker.crack()
        # except:
        #     logger.exception('出错')
        time.sleep(5)
        if driver.title == '投稿 - 哔哩哔哩弹幕视频网 - ( ゜- ゜)つロ 乾杯~ - bilibili':
            cookie = driver.get_cookies()
            print(cookie)
            with open(filename, "w") as f:
                json.dump(cookie, f)
            logger.info('更新cookie成功')
        else:
            logger.info('更新cookie失败') 
Example #5
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def get_last_seen(self, name, timeout=10):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)  # we will send the name to the input key box
        last_seen_css_selector = "._315-i"
        start_time = dt.datetime.now()
        try:
            WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.CSS_SELECTOR, last_seen_css_selector)))
            while True:
                last_seen = self.browser.find_element_by_css_selector(last_seen_css_selector).text
                if last_seen and "click here" not in last_seen:
                    return last_seen
                end_time = dt.datetime.now()
                elapsed_time = (end_time-start_time).seconds
                if elapsed_time > 10:
                    return "None"
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException:
            return "None"
        except Exception:
            return "None"

    # This method does not care about anything, it sends message to the currently active chat
    # you can use this method to recursively send the messages to the same person 
Example #6
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def send_blind_message(self, message):
        try:
            message = self.emojify(message)
            send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
            messages = message.split("\n")
            for msg in messages:
                send_msg.send_keys(msg)
                send_msg.send_keys(Keys.SHIFT+Keys.ENTER)
            send_msg.send_keys(Keys.ENTER)
            return True
        except NoSuchElementException:
            return "Unable to Locate the element"
        except Exception as e:
            print(e)
            return False

    # This method will send you the picture 
Example #7
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def clear_chat(self, name):
        self.browser.find_element_by_css_selector("._3FRCZ").send_keys(name+Keys.ENTER)
        menu_xpath = "/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[3]/div/span"
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, menu_xpath)))
        menu = self.browser.find_element_by_xpath(menu_xpath)
        menu.click()
        chains = ActionChains(self.browser)
        for i in range(4):
            chains.send_keys(Keys.ARROW_DOWN)
        chains.send_keys(Keys.ENTER)
        chains.perform()
        clear_xpath = '//*[@id="app"]/div/span[2]/div/div/div/div/div/div/div[2]/div[2]'
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, clear_xpath)))
        self.browser.find_element_by_xpath(clear_xpath).click()



    # override the timeout 
Example #8
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def get_profile_pic(self, name):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)
        try:
            open_profile = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div[1]/div/div/div[3]/div/header/div[1]/div/img")))
            open_profile.click()
        except:
            print("nothing found")
        try:
            open_pic =  WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div[1]/div/div/div[1]/div[3]/span/div/span/div/div/div/div[1]/div[1]/div/img")))
            open_pic.click()
        except:
            print("Nothing found")
        try:
            img = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                    (By.XPATH,'//*[@id="app"]/div/span[2]/div/div/div[2]/div/div/div/div/img')))
        except:
            print("Couldn't find the URL to the image")
        img_src_url = img.get_attribute('src')
        self.browser.get(img_src_url)
        self.browser.save_screenshot(name+"_img.png") 
Example #9
Source File: bots.py    From Dallinger with MIT License 6 votes vote down vote up
def sign_off(self):
        """Submit questionnaire and finish.

        This uses Selenium to click the submit button on the questionnaire
        and return to the original window.
        """
        try:
            logger.info("Bot player signing off.")
            feedback = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.ID, "submit-questionnaire"))
            )
            self.complete_questionnaire()
            feedback.click()
            logger.info("Clicked submit questionnaire button.")
            self.driver.switch_to_window(self.driver.window_handles[0])
            self.driver.set_window_size(1024, 768)
            logger.info("Switched back to initial window.")
            return True
        except TimeoutException:
            logger.error("Error during experiment sign off.")
            return False 
Example #10
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def __init__(self, wait, screenshot=None, session=None):
        chrome_options = Options()
        if session:
            chrome_options.add_argument("--user-data-dir={}".format(session))
            self.browser = webdriver.Chrome(options=chrome_options)  # we are using chrome as our webbrowser
        else:
            self.browser = webdriver.Chrome()
        self.browser.get("https://web.whatsapp.com/")
        # emoji.json is a json file which contains all the emojis
        with open("emoji.json") as emojies:
            self.emoji = json.load(emojies)  # This will load the emojies present in the json file into the dict
        WebDriverWait(self.browser,wait).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, '._3FRCZ')))
        if screenshot is not None:
            self.browser.save_screenshot(screenshot)  # This will save the screenshot to the specified file location

    # This method is used to send the message to the individual person or a group
    # will return true if the message has been sent, false else 
Example #11
Source File: apw_internal.py    From tir with MIT License 6 votes vote down vote up
def SwitchModal(self, option, frame=''):
        '''
        Sets the focus in a modal object
        '''
        try:
            time.sleep(2)
            self.driver.switch_to.default_content()
            self.driver.implicitly_wait(30)
            modaldupGuia = self.wait.until(EC.presence_of_element_located((By.ID, "modal-content")))

            if modaldupGuia.is_displayed():
                btn = self.driver.find_element_by_xpath("//button[contains(text(), '%s')]" % option)
                btn.click()
            else:
                time.sleep(2)
                if modaldupGuia.is_displayed():
                    btn = self.driver.find_element_by_xpath("//button[contains(text(), '%s')]" % option)
                    btn.click()
        except Exception as e:
            self.log_error(str(e)) 
Example #12
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def send_anon_message(self, phone, text):
        payload = urlencode({"phone": phone, "text": text, "source": "", "data": ""})
        self.browser.get("https://api.whatsapp.com/send?"+payload)
        try:
            Alert(self.browser).accept()
        except:
            print("No alert Found")
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#action-button")))
        send_message = self.browser.find_element_by_css_selector("#action-button")
        send_message.click()
        confirm = WebDriverWait(self.browser, self.timeout+5).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
        confirm.clear()
        confirm.send_keys(text+Keys.ENTER)

    # Check if the message is present in an user chat 
Example #13
Source File: webdriver.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scan_webdriver(self):
        self.browser.get(self.entry_url)

        try:
            WebDriverWait(self.browser, 30).until(
                EC.presence_of_element_located((By.TAG_NAME, "body"))
            )
        except TimeoutException as e:
            messages.error(self.request, e)

        self.browser.delete_all_cookies()
        self.browser.add_cookie(self.wtm_cookie)
        self.browser.add_cookie(self.wtm_debug_cookie)
        self.browser.get(self.entry_url)

        for cookie in self.browser.get_cookies():
            self.process_webdriver_cookie(cookie)

        self.browser.quit() 
Example #14
Source File: test_helper.py    From python-client with Apache License 2.0 6 votes vote down vote up
def wait_for_element(driver: 'WebDriver', locator: str, value: str, timeout: int = SLEEPY_TIME) -> 'WebElement':
    """Wait until the element located

    Args:
        driver: WebDriver instance
        locator: Locator like WebDriver, Mobile JSON Wire Protocol
            (e.g. `appium.webdriver.common.mobileby.MobileBy.ACCESSIBILITY_ID`)
        value: Query value to locator
        timeout: Maximum time to wait the element. If time is over, `TimeoutException` is thrown

    Raises:
        `selenium.common.exceptions.TimeoutException`

    Returns:
        The found WebElement
    """
    return WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((locator, value))
    ) 
Example #15
Source File: readcomic.py    From ReadComicOnline-Downloader with MIT License 6 votes vote down vote up
def Single_Issue(url,Quality):
	#print url
	print 'Quality To Download : ',Quality[0]
	print 'Order To Download : ',Quality[1]
	#sys.exit()
	#print url,' This is first'
	
	browser = webdriver.PhantomJS(service_args=['--load-images=no'])
	browser.get(url)
	try:
		element = WebDriverWait(browser, 10).until(
			EC.presence_of_element_located((By.ID, "stSegmentFrame"))
		)
		#print 'Downloading the whole page! Will take some time, please don\'t close this script...\n'
		#print 'I\'ve waited long enough'
	except Exception, e:
		#raise e
		browser.save_screenshot('Single_exception.png')
		print e
		pass 
Example #16
Source File: CompanyScraper.py    From scrape-linkedin-selenium with MIT License 6 votes vote down vote up
def load_initial(self, company):
        url = 'https://www.linkedin.com/company/{}'.format(company)

        self.driver.get(url)
        try:
            myElem = WebDriverWait(self.driver, self.timeout).until(AnyEC(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.organization-outlet')),
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.error-container'))
            ))
        except TimeoutException as e:
            raise ValueError(
                """Took too long to load company.  Common problems/solutions:
                1. Invalid LI_AT value: ensure that yours is correct (they
                   update frequently)
                2. Slow Internet: increase the timeout parameter in the Scraper constructor""")
        try:
            self.driver.find_element_by_css_selector('.organization-outlet')
        except:
            raise ValueError(
                'Company Unavailable: Company link does not match any companies on LinkedIn') 
Example #17
Source File: exercise_file.py    From Lyndor with MIT License 6 votes vote down vote up
def regular_login(url, course_folder, driver):
    driver.get("https://www.lynda.com/signin/")          # launch lynda.com/signin

    # enter username
    email = driver.find_element_by_css_selector("#email-address")
    email.clear()
    email.send_keys(read.username)
    driver.find_element_by_css_selector('#username-submit').click()
    print('\nusername successfully entered ....')
    # wait for password field to appear
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#password-input")))
    # enter password
    passwrd = driver.find_element_by_css_selector('#password-input')
    passwrd.send_keys(read.password)
    driver.find_element_by_css_selector('#password-submit').click()
    print('password successfully entered ....') 
Example #18
Source File: ConnectionScraper.py    From scrape-linkedin-selenium with MIT License 6 votes vote down vote up
def get_first_connections(self):
        try:
            see_connections_link = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '.pv-top-card-v2-section__link--connections'
            )))
        except TimeoutException as e:
            print("""Took too long to load connections link. This usually indicates you were trying to
scrape the connections of someone you aren't connected to.""")
            return []

        see_connections_link.click()
        try:
            self.configure_connection_type()
        except TimeoutException:
            return []
        all_conns = [] 
Example #19
Source File: gp_privacy_crawler.py    From crawler with MIT License 6 votes vote down vote up
def get_privacy(driver, package_name):
    try:
        url = "https://play.google.com/store/apps/details?id={0}&hl=en".format(package_name)
        driver.get(url)
        driver.maximize_window()
        driver.find_element_by_link_text("View details").click()
        tmp = (By.CLASS_NAME, "fnLizd")
        WebDriverWait(driver, 20).until(EC.presence_of_element_located(tmp))
        page_source = driver.page_source
        if "send SMS messages" in page_source:
            print("找到含有SMS权限的APP: {0}".format(package_name))
            with open("privacy_with_sms.txt", "a+") as f:
                f.write(package_name + "\n")
            return package_name
        return False
    except Exception as e:
        print(e)
        return False 
Example #20
Source File: tests.py    From niji with MIT License 6 votes vote down vote up
def test_stick_to_top_admin(self):
        self.browser.get(self.live_server_url + reverse("niji:index"))
        login(self.browser, 'super', '123')
        self.assertIn("Log out", self.browser.page_source)

        lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50))

        self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={"pk": lucky_topic1.pk}))
        self.browser.find_element_by_class_name('move-topic-up').click()
        up_level = WebDriverWait(
            self.browser, 10
        ).until(
            expected_conditions.presence_of_element_located(
                (By.NAME, 'move-topic-up-level')
            )
        )
        up_level = Select(up_level)
        up_level.select_by_visible_text('1')
        time.sleep(1)
        self.browser.execute_script("$('.modal-confirm').click()")
        self.browser.get(self.live_server_url+reverse('niji:index'))
        first_topic_title = self.browser.find_elements_by_class_name('entry-link')[0].text

        self.assertEqual(first_topic_title, lucky_topic1.title) 
Example #21
Source File: base.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def click_through_close(self, button, wait, screenshot=None):
        """Click a button or link and wait for something to disappear."""
        try:
            button.click()
        except ElementNotVisibleException:
            self.browser.execute_script(
                "return arguments[0].scrollIntoView();", button)
            button.click()

        if screenshot is not None:
            self.get_screenshot(screenshot)
        try:
            WebDriverWait(self.browser, 10).until_not(
                EC.presence_of_element_located(wait)
            )
        except TimeoutException:
            self.get_screenshot('exception')
            raise 
Example #22
Source File: spider_lagou.py    From spider_python with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        使用selenium取爬虫
        :return:
        """

        # 1.open the base_url
        self.driver.get(self.base_url)

        while True:

            # 2.get detail page url
            # 适用于第 1 页,第 2 页,第 3 页
            source = self.driver.page_source

            # 2.1 wait for the element had be presented【 下一页 】
            WebDriverWait(driver=self.driver, timeout=20).until(
                EC.presence_of_element_located((By.XPATH, "//div[@class='pager_container']/span[last()]"))
            )

            # 3.parse the first page
            self.parse_list_page(source)

            # 4.use selenium to click the next page
            # 找到最后一个 span 标签:下一页
            next_btn = self.driver.find_element_by_xpath("//div[@class='pager_container']/span[last()]")

            # 5.perform the click method
            # 注意:确保不是在最后一页
            if "pager_next_disabled" in next_btn.get_attribute('class'):
                # 最后一页面的时候,退出应用
                self.driver.quit()
                break
            else:
                next_btn.click()

            # 6.爬一页完成,就休息 1 秒钟
            time.sleep(1) 
Example #23
Source File: PyWhatsapp.py    From PyWhatsapp with Apache License 2.0 5 votes vote down vote up
def send_message(target):
    global message, wait, browser
    try:
        x_arg = '//span[contains(@title,' + target + ')]'
        ct = 0
        while ct != 10:
            try:
                group_title = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
                group_title.click()
                break
            except:
                ct += 1
                time.sleep(3)
        input_box = browser.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
        for ch in message:
            if ch == "\n":
                ActionChains(browser).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
            else:
                input_box.send_keys(ch)
        input_box.send_keys(Keys.ENTER)
        print("Message sent successfuly")
        time.sleep(1)
    except NoSuchElementException:
        return 
Example #24
Source File: test_views.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def test_all_patients_correct_order(self):

        self.selenium.get('%s%s' % (self.live_server_url, '/'))
        self.submit_login(self.providers['coordinator'].username,
                          self.provider_password)

        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("all-patients")))

        # causes a broken pipe error
        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("all-patients")))

        self.assertEquals(self.selenium.current_url,
                          '%s%s' % (self.live_server_url,
                                    reverse('all-patients')))

        # unsure how to test for multiple elements/a certain number of elements
        # WebDriverWait(self.selenium, 60).until(EC.presence_of_element_located((By.ID, "ptlast")))
        # WebDriverWait(self.selenium, 60).until(EC.presence_of_element_located((By.ID, "ptlatest")))

        # test ordered by last name
        pt_tbody = self.selenium.find_element_by_xpath("//div[@class='container']/table/tbody") # this line does throw an error if the id-ed element does not exist
        first_patient_name = pt_tbody.find_element_by_xpath("//tr[2]/td[1]").text
        second_patient_name = pt_tbody.find_element_by_xpath("//tr[3]/td[1]").text
        self.assertLessEqual(first_patient_name, second_patient_name)
        self.assertEqual(first_patient_name, "Action, No I.")

        # # test order by latest activity
        # # more difficult to test attributes, I'm just testing that the first
        # # name is correct
        # pt_last_tbody = self.selenium.find_element_by_xpath(
        #     "//div[@id='ptlatest']/table/tbody")
        # first_patient_name = pt_last_tbody.find_element_by_xpath(
        #     ".//tr[2]/td[1]/a").get_attribute("text")
        # self.assertEqual(first_patient_name, "Brodeltein, Juggie B.") 
Example #25
Source File: main.py    From damaiTi9 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def detail_page_auto(self):
        """详情页自动"""

        self.driver.get('https://detail.damai.cn/item.htm?id=593089517773')
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//button[@data-spm="dconfirm"]')))

        dconfirm_button = self.driver.find_element_by_xpath('//button[@data-spm="dconfirm"]')
        while dconfirm_button.get_attribute('class') == 'privilege_sub disabled':
            print(dconfirm_button.get_attribute('class'), '确定按钮无法点击,刷新页面')
            self.driver.refresh()
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '//button[@data-spm="dconfirm"]')))
            try:
                dconfirm_button = self.driver.find_element_by_xpath('//button[@data-spm="dconfirm"]')
            except Exception as e:
                print('寻找按钮失败', e)

        self.driver.find_element_by_css_selector("#privilege_val").send_keys(self.dotakey)
        dconfirm_button.click()
        if self.quantity != 1:
            try:
                self.driver.find_element_by_xpath(
                    '//a[@class="cafe-c-input-number-handler cafe-c-input-number-handler-up"]').click()
            except Exception as e:
                print("未成功点击+号", e)
        self.driver.find_element_by_xpath(f'//div[@class="select_right_list"]/div[{self.round}]/span[2]').click()
        dbuy_button = self.driver.find_element_by_xpath('//div[@data-spm="dbuy"]')
        print('寻找按钮:', dbuy_button.text)
        dbuy_button.click() 
Example #26
Source File: upload.py    From bilibiliupload with MIT License 5 votes vote down vote up
def add_videos(self, driver, title_, videopath):
        WebDriverWait(driver, 20).until(
            ec.presence_of_element_located((By.NAME, 'buploader')))
        upload = driver.find_element_by_name('buploader')
        # print(driver.title)
        # logger.info(driver.title)
        upload.send_keys(videopath)  # send_keys
        logger.info('开始上传' + title_)
        time.sleep(2)
        button = r'//*[@class="new-feature-guide-v2-container"]/div/div/div/div/div[1]'
        if self.is_element_exist(driver, button):
            sb = driver.find_element_by_xpath(button)
            sb.click()
            sb.click()
            sb.click()
            logger.debug('点击')
        while True:
            try:
                info = driver.find_elements_by_class_name(r'item-upload-info')
                for t in info:
                    if t.text != '':
                        print(t.text)
                time.sleep(10)
                text = driver.find_elements_by_xpath(r'//*[@class="item-upload-info"]/span')
                aggregate = set()
                for s in text:
                    if s.text != '':
                        aggregate.add(s.text)
                        print(s.text)

                if len(aggregate) == 1 and ('Upload complete' in aggregate or '上传完成' in aggregate):
                    break
            except selenium.common.exceptions.StaleElementReferenceException:
                logger.exception("selenium.common.exceptions.StaleElementReferenceException")
        logger.info('上传%s个数%s' % (title_, len(info))) 
Example #27
Source File: main.py    From damaiTi9 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def login(self):
        """登陆模块"""

        self.driver.get('https://passport.damai.cn/login')
        # WebDriverWait(self.driver, 10).until(
        #     EC.presence_of_element_located((By.ID, 'alibaba-login-box')))
        # self.driver.switch_to.frame('alibaba-login-box')
        # self.driver.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys(self.phone_num)
        # self.driver.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys(self.passwd)

        WebDriverWait(self.driver, 3000).until(
            EC.presence_of_element_located((By.XPATH, '//a[@data-spm="duserinfo"]/div')))
        print('登陆成功')
        user_name = self.driver.find_element_by_xpath('//a[@data-spm="duserinfo"]/div').text
        print('账号:', user_name) 
Example #28
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 5 votes vote down vote up
def send_message(self, name, message):
        message = self.emojify(message)  # this will emojify all the emoji which is present as the text in string
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)  # we will send the name to the input key box
        try:
            send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
            messages = message.split("\n")
            for msg in messages:
                send_msg.send_keys(msg)
                send_msg.send_keys(Keys.SHIFT+Keys.ENTER)
            send_msg.send_keys(Keys.ENTER)
            return True
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException:
            return False
        except Exception:
            return False

    # This method will count the no of participants for the group name provided 
Example #29
Source File: Scraper.py    From scrape-linkedin-selenium with MIT License 5 votes vote down vote up
def wait_for_el(self, selector):
        return self.wait(EC.presence_of_element_located((
            By.CSS_SELECTOR, selector
        ))) 
Example #30
Source File: ConnectionScraper.py    From scrape-linkedin-selenium with MIT License 5 votes vote down vote up
def load_profile_page(self, url='', user=None):
        """Load profile page and all async content

        Params:
            - url {str}: url of the profile to be loaded
        Raises:
            ValueError: If link doesn't match a typical profile url
        """
        if user:
            url = 'http://www.linkedin.com/in/' + user
        if 'com/in/' not in url:
            raise ValueError("Url must look like ...linkedin.com/in/NAME")
        self.current_profile = url.split(r'com/in/')[1]
        self.driver.get(url)
        # Wait for page to load dynamically via javascript
        try:
            myElem = WebDriverWait(self.driver, self.timeout).until(AnyEC(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.pv-top-card-section')),
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.profile-unavailable'))
            ))
        except TimeoutException as e:
            raise Exception(
                """Took too long to load profile.  Common problems/solutions:
                1. Invalid LI_AT value: ensure that yours is correct (they
                   update frequently)
                2. Slow Internet: increase the timeout parameter in the Scraper constructor""")

        # Check if we got the 'profile unavailable' page
        try:
            self.driver.find_element_by_css_selector('.pv-top-card-section')
        except:
            raise ValueError(
                'Profile Unavailable: Profile link does not match any current Linkedin Profiles')