How to use close_browser method in websmith

Best Python code snippet using websmith_python

bot.py

Source:bot.py Github

copy

Full Screen

...3334 self.browser = webdriver.Chrome(ChromeDriverManager().install())3536 # метод для закрытия браузера37 def close_browser(self):3839 self.browser.close()40 self.browser.quit()4142 # метод логина43 def login(self):4445 browser = self.browser46 browser.get('https://www.instagram.com')47 time.sleep(random.randrange(5, 7))4849 username_input = browser.find_element_by_name('username')50 username_input.clear()51 username_input.send_keys(username)5253 time.sleep(2)5455 password_input = browser.find_element_by_name('password')56 password_input.clear()57 password_input.send_keys(password)5859 password_input.send_keys(Keys.ENTER)60 time.sleep(10)6162 # метод ставит лайки по hashtag63 def like_photo_by_hashtag(self, hashtag):6465 for item in hashtag:66 browser = self.browser67 browser.get(f'https://www.instagram.com/explore/tags/{item}/')686970 for i in range(1, 2):71 browser.execute_script("window.scrollTo(0, 100)")72 time.sleep(random.randrange(3, 5))7374 hrefs = browser.find_elements_by_tag_name('a')75 posts_urls = [item.get_attribute('href') for item in hrefs if "/p/" in item.get_attribute('href')]76 set(posts_urls)777879 for url in posts_urls[0:3]:80 try:81 browser.get(url)82 time.sleep(8)83 like_button = browser.find_element_by_xpath(84 '/html/body/div[1]/section/main/div/div[1]/article/div[3]/section[1]/span[1]/button').click()85 name_btn = '/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div/span/a'86 browser.find_element_by_xpath(name_btn).click()87 time.sleep(8)88 sub_btn = '/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/div/div/div/span/span[1]/button'89 browser.find_element_by_xpath(sub_btn).click()90 time.sleep(5)91 browser.back()92 browser.back()93 time.sleep(random.randrange(10))949596 except Exception as ex:97 print(ex)98 self.close_browser()99100101 time.sleep(5)102103 104105 # метод проверяет по xpath существует ли элемент на странице106 def xpath_exists(self, url):107108 browser = self.browser109 try:110 browser.find_element_by_xpath(url)111 exist = True112113114 except NoSuchElementException:115 exist = False116117 return exist118119 # метод собирает ссылки на все посты пользователя120 def get_all_posts_urls(self, userpage):121122 browser = self.browser123 browser.get(userpage)124 time.sleep(4)125126 wrong_userpage = "/html/body/div[1]/section/main/div/h2"127 if self.xpath_exists(wrong_userpage):128 print("Такого пользователя не существует, проверьте URL")129 self.close_browser()130131132 else:133 print("Пользователь успешно найден, ставим лайки!")134 time.sleep(2)135136 posts_count = int(browser.find_element_by_xpath(137 "/html/body/div[1]/section/main/div/header/section/ul/li[1]/span/span").text)138 loops_count = int(posts_count / 12)139 140141 posts_urls = []142143144 for i in range(0, loops_count):145 hrefs = browser.find_elements_by_tag_name('a')146 hrefs = [item.get_attribute('href') for item in hrefs if "/p/" in item.get_attribute('href')]147148 for href in hrefs:149 posts_urls.append(href)150151 browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")152 time.sleep(random.randrange(2, 4))153 print(f"Итерация #{i}")154155 file_name = userpage.split("/")[-2]156157 with open(f'{file_name}.txt', 'a') as file:158 for post_url in posts_urls:159 file.write(post_url + "\n")160161 set_posts_urls = set(posts_urls)162 set_posts_urls = list(set_posts_urls)163164 with open(f'{file_name}_set.txt', 'a') as file:165 for post_url in set_posts_urls:166 file.write(post_url + '\n')167168 # метод ставит лайки по ссылке на аккаунт пользователя169 def put_many_likes(self, userpage):170171 browser = self.browser172 self.get_all_posts_urls(userpage)173 file_name = userpage.split("/")[-2]174 time.sleep(4)175 browser.get(userpage)176 time.sleep(4)177178 with open(f'{file_name}_set.txt') as file:179 urls_list = file.readlines()180181 for post_url in urls_list[0:6]:182 try:183 browser.get(post_url)184 time.sleep(2)185186 like_button = "/html/body/div[1]/section/main/div/div/article/div[3]/section[1]/span[1]/button"187 browser.find_element_by_xpath(like_button).click()188 # time.sleep(random.randrange(80, 100))189 time.sleep(2)190191 print(f"Лайк на пост: {post_url} успешно поставлен!")192193194 except Exception as ex:195 print(ex)196 self.close_browser()197198 self.close_browser()199200 # метод ставит лайк на пост по прямой ссылке201 def put_exactly_like(self, userpost):202203 browser = self.browser204 browser.get(userpost)205 time.sleep(4)206207 wrong_userpage = "/html/body/div[1]/section/main/div/h2"208 if self.xpath_exists(wrong_userpage):209 print("Такого поста не существует, проверьте URL")210 self.close_browser()211212213 else:214 print("Пост успешно найден, ставим лайк!")215 time.sleep(2)216217 like_button = "/html/body/div[1]/section/main/div/div/article/div[3]/section[1]/span[1]/button"218 browser.find_element_by_xpath(like_button).click()219 time.sleep(2)220221 print(f"Лайк на пост: {userpost} поставлен!")222 self.close_browser()223 224225 self.close_browser()226227228 def download_userpage_content(self, userpage):229230 browser = self.browser231 self.get_all_posts_urls(userpage)232 file_name = userpage.split("/")[-2]233 time.sleep(4)234 browser.get(userpage)235 time.sleep(4)236237 # создаём папку с именем пользователя для чистоты проекта238 if os.path.exists(f"{file_name}"):239 print("Папка уже существует!")240241242 else:243 os.mkdir(file_name)244245 img_and_video_src_urls = []246247248 with open(f'{file_name}_set.txt') as file:249 urls_list = file.readlines()250251 for post_url in urls_list:252 try:253 browser.get(post_url)254 time.sleep(4)255256 img_src = "/html/body/div[1]/section/main/div/div[1]/article/div[2]/div/div/div[1]/img"257 video_src = "/html/body/div[1]/section/main/div/div[1]/article/div[2]/div/div/div[1]/div/div/video"258 post_id = post_url.split("/")[-2]259260 if self.xpath_exists(img_src):261 img_src_url = browser.find_element_by_xpath(img_src).get_attribute("src")262 img_and_video_src_urls.append(img_src_url)263264 # сохраняем изображение265 get_img = requests.get(img_src_url)266 with open(f"{file_name}/{file_name}_{post_id}_img.jpg", "wb") as img_file:267 img_file.write(get_img.content)268269 elif self.xpath_exists(video_src):270 video_src_url = browser.find_element_by_xpath(video_src).get_attribute("src")271 img_and_video_src_urls.append(video_src_url)272273 # сохраняем видео274 get_video = requests.get(video_src_url, stream=True)275 with open(f"{file_name}/{file_name}_{post_id}_video.mp4", "wb") as video_file:276 for chunk in get_video.iter_content(chunk_size=1024 * 1024):277 if chunk:278 video_file.write(chunk)279 else:280 # print("Упс! Что-то пошло не так!")281 img_and_video_src_urls.append(f"{post_url}, нет ссылки!")282 print(f"Контент из поста {post_url} успешно скачан!")283284 except Exception as ex:285 print(ex)286 self.close_browser()287288 self.close_browser()289290 with open(f'{file_name}/{file_name}_img_and_video_src_urls.txt', 'a') as file:291 for i in img_and_video_src_urls:292 file.write(i + "\n")293294295 def get_all_followers(self, user):296 297 browser = self.browser298 browser.get(user)299 time.sleep(4)300 file_name = user.split('/')[-2]301302 # Папка с именем пользователя для чистоты303304 if os.path.exists(f'{file_name}'):305 print(f'Папка есть {file_name}')306307 else:308 print(f'Создаем пользователя {file_name}')309 os.mkdir(f'{file_name}')310311312 wrong_userpage = "/html/body/div[1]/section/main/div/h2"313 if self.xpath_exists(wrong_userpage):314 print("Такого пользователя не существует, проверьте URL")315 self.close_browser()316317 else:318 print("Пользователь успешно найден, скачиваем ссылки!") 319 time.sleep(2)320 follower_btn = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/a/span') 321 #follower_count = follower_btn.text322 #follower_count = int(follower_count.split(' ')[0])323 follower_count = follower_btn.get_attribute('title')324325 if ' ' in follower_count:326 follower_count = int(''.join(follower_count.split(' ')))327328 else:329 follower_count = int(follower_count)330331 print(f'Количество подписчиков: {follower_count}')332 time.sleep(2)333334 loop_count = int(follower_count / 12)335 print(f'Число итераций {loop_count}')336 time.sleep(2)337 338 follower_btn.click()339 time.sleep(2)340 341 followers_ul = browser.find_element_by_xpath('/html/body/div[5]/div/div/div[2]')342 343 try:344 followers_urls = []345346 347 for i in range(1, loop_count + 1):348 browser.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', followers_ul)349 time.sleep(2)350 print(f'Итерация #{i}')351352353354 all_urls_div = followers_ul.find_elements_by_tag_name('li')355356 for url in all_urls_div:357 url = url.find_element_by_tag_name('a').get_attribute('href')358 followers_urls.append(url)359360 # сохраняем всех подписчиков в файл361 with open(f'{file_name}/{file_name}.txt', 'a') as text_file:362 for link in followers_urls:363 text_file.write(link + '\n')364365 with open(f'{file_name}/{file_name}.txt', 'a') as text_file:366 users_urls = text_file.readlines()367368 for user in users_urls[0:10]:369 try:370371 try:372 373 with open(f'{file_name}/{file_name}.sub_list.txt', 'r') as sub_list_file:374 lines = sub_list_file.readlines()375 if user in lines:376 print(f'Мы уже подписан на {user}, слудующий юзер')377 continue378379380 except Exception as ex:381 print('Файл с ссылками нет')382 print(ex)383 self.close_browser()384385 browser = self.browser386 browser.get(user)387 page_owner = user.split('/')[-2]388389 if self.xpath_exists('/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/a'):390391 print('Это профиль мой')392393 elif self.path.exists('/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/div/div[2]/div/span/span[1]/button/div/span'):394 print('Мы уже подписаны на {page_owner} пропускаем итерацию') 395396 else:397 time.sleep(2)398399 if self.xpath_exists('/html/body/div[1]/section/main/div/div/article/div[1]/div/h2'):400 401 try:402 follow_btn = browser.find_element_by_xpath(403 '/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/button'404 ).click()405 print(f'Запросили подписку на юзера {page_owner}. Закрытый акк!')406407408 except Exception as ex:409 print(ex)410411412 else:413414415 try:416417418 if self.path_exists('/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/button'):419 follower_btn = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/button').click()420 print(f'Подписались на {page_owner} Открытый акк')421422423 else:424 follower_btn = browser.find_element_by_xpath(425 '/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/div/span/span[1]/button'426 ).click() 427 print(f'Подписались на юзера{page_owner} Открытый акк')428429 except Exception as e:430 431 print(e) 432 # записываем данные в файл для ссылок всех подписок если файла нет, создаем, если есть - дополняем433 with open(f'{file_name}/{file_name}_sub_list.txt', 'a') as sub_list_file:434 sub_list_file.write(user)435436437 time.sleep(7)438439440 except Exception as ex:441 print(ex) 442 443444 except Exception as ex:445446 print(ex)447 448 self.close_browser() 449450 451# метод для отправки сообщений452 def send_message(self, user="", message=""):453454 browser = self.browser455 time.sleep(2)456457 msg_btn = browser.find_element_by_xpath('/html/body/div[1]/section/nav/div[2]/div/div/div[3]/div/div[2]/a')458459 460 msg_btn.click()461 time.sleep(2)462463 # отключаем всплывающее окно464 if self.xpath_exists('/html/body/div[5]/div/div/div'):465 browser.find_element_by_xpath('/html/body/div[5]/div/div/div/div[3]/button[2]').click()466 time.sleep(4) 467468 # вводим получателя469 btn = browser.find_element_by_xpath('/html/body/div[1]/section/div/div[2]/div/div/div[2]/div/div[3]/div/button').click()470 to_input = browser.find_element_by_xpath('/html/body/div[5]/div/div/div[2]/div[1]/div/div[2]/input')471 to_input.send_keys(user)472 time.sleep(2)473474 # выбираем получателя из списка475 user_list = browser.find_element_by_xpath('/html/body/div[5]/div/div/div[2]/div[2]').find_element_by_tag_name('button').click()476 time.sleep(2)477 next = browser.find_element_by_xpath('/html/body/div[5]/div/div/div[1]/div/div[2]/div/button').click()478 time.sleep(2)479 message_btn = browser.find_element_by_xpath('/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea')480 message_btn.clear()481 message_btn.send_keys(message)482 time.sleep(2)483 message_btn.send_keys(Keys.ENTER)484 self.close_browser()485 486487for user, user_data in users_settings_dict.items():488 username = user_data['login']489 password = user_data['password']490 bot = InstagramBot(username, password)491 bot.login()492 bot.like_photo_by_hashtag(493 [494 #'программирование', 495 #'js', 496 'вебразработка',497 'react'498 ]499 )500501 502 #bot.get_all_followers('https://www.instagram.com/angdigsthepunkrocks/')503 bot.close_browser()504 time.sleep(2)505506507508509#bot = InstagramBot(username1, password2)510#bot.login()511#bot.like_photo_by_hashtag('surfing')512#bot.send_message('fedorchenkovlad9', 'hee are you here?') ...

Full Screen

Full Screen

SahiRobotBridgeTest.py

Source:SahiRobotBridgeTest.py Github

copy

Full Screen

...18 time.sleep(3)19 except Exception, e:20 self.assertEquals(str(e), "Browser was not launched. Please check your test script and make sure Sahi is running.", "Browser launch error was expected.")21 finally:22 helper.close_browser()23 24 25 def testFunctionNotFound(self):26 27 helper = SahiRobotBridge(self.host , self.port)28 helper.open_browser("chrome", "http://sahi.co.in/demo")29 helper.load_script("D:/sahi/sahi_pro_g/userdata/scripts/demo/robot_sample.sah")30 try:31 helper.execute_function("login_not", '"test","secret"')32 except Exception, e:33 self.assertEquals(str(e), 'function execution failed for login_not("test","secret").', "wrong error message")34 35 finally:36 helper.close_browser()37 38 def testExecuteFunction(self):39 helper = SahiRobotBridge(self.host , self.port)40 try:41 helper.open_browser("chrome", "http://sahi.co.in/demo")42 helper.load_script("D:/sahi/sahi_pro_g/userdata/scripts/demo/robot_sample.sah")43 helper.execute_function("login", '"test","secret"')44 except Exception, e:45 self.assertEquals(str(e), 'function execution failed for login("test","secret").', "wrong error message")46 finally:47 helper.close_browser()48 49 50 def testLoadAvailableScript(self):51 helper = SahiRobotBridge(self.host , self.port)52 try:53 helper.open_browser("chrome", "http://sahi.co.in/demo")54 helper.load_script("D:/sahi/sahi_pro_g/userdata/scripts/demo/robot_sample.sah")55 except Exception, e:56 self.assertEqual(str(e), "script loading failed for robot_sample.sah", "wrong error message")57 finally:58 helper.close_browser()59 60 def testLoadUnavailableScript(self):61 helper = SahiRobotBridge(self.host , self.port)62 try:63 helper.open_browser("chrome", "http://sahi.co.in/demo")64 helper.load_script("D:/sahi/sahi_pro_g/userdata/scripts/demo/robot_sample_not.sah")65 except Exception, e:66 self.assertEqual(str(e), "Script load failed for robot_sample_not.sah.")67 finally:68 helper.close_browser()69 70 def testFunctionFail(self):71 helper = SahiRobotBridge(self.host , self.port)72 try:73 helper.open_browser("chrome", "http://sahi.co.in/demo")74 helper.load_script("D:/sahi/sahi_pro_g/userdata/scripts/demo/robot_sample_fail.sah")75 helper.execute_function("login", '"test","secret"')76 except Exception, e:77 self.assertEquals(str(e), 'function execution failed for login("test","secret").', "wrong error message")78 finally:...

Full Screen

Full Screen

test_base.py

Source:test_base.py Github

copy

Full Screen

...18 self.base = BaseScrapper()19 self.base.open_browser()20 def tearDown(self):21 if self.base.browser is not None:22 self.base.close_browser()23 def test_open_mobile_browser(self):24 self.base.close_browser()25 self.base.open_browser()26 self.assertIsNotNone(self.base.browser)27 def test_open_mobile_browser_hidden(self):28 CONFIG.update({'hide_browser': True})29 self.base.close_browser()30 self.base.open_browser()31 self.assertIsNotNone(self.base.browser)32 def test_close_browser(self):33 self.base.close_browser()34 self.assertIsNone(self.base.browser)35 def test_wait_sleep_time_none_explicit_false(self):36 with patch('random.randrange', return_value=SLEEP):37 waited = self.base.wait(explicit=False)38 self.assertEqual(waited, SLEEP)39 def test_wait_sleep_time_none_explicit_true(self):40 with patch('random.randrange', return_value=SLEEP):41 waited = self.base.wait(explicit=True)42 self.assertEqual(waited, SLEEP)43 def test_wait_sleep_time_defined(self):44 waited = self.base.wait(sleep_time=SLEEP, explicit=True)45 self.assertEqual(waited, SLEEP)46 def test_get_page(self):47 result = self.base.get_page('accounts/login')...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run websmith automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful