|
| 1 | +from selenium import webdriver |
| 2 | +import time |
| 3 | +from selenium.webdriver.common.by import By |
| 4 | +from selenium.webdriver.support.wait import WebDriverWait |
| 5 | +from selenium.webdriver.support import expected_conditions as EC |
| 6 | +import urllib.parse |
| 7 | +import datetime |
| 8 | +import os |
| 9 | + |
| 10 | +# options = webdriver.ChromeOptions() |
| 11 | +# # options.add_argument("start-maximized") |
| 12 | +# options.add_experimental_option("excludeSwitches", ["enable-automation"]) |
| 13 | +# options.add_experimental_option('useAutomationExtension', False) |
| 14 | + |
| 15 | +options = webdriver.FirefoxOptions() |
| 16 | +options.add_argument("--headless") |
| 17 | +options.add_argument("--window-size=1920,1080") |
| 18 | +options.add_argument("--disable-gpu") |
| 19 | +options.add_argument("--disable-extensions") |
| 20 | +options.add_argument("--no-sandbox") |
| 21 | +options.add_argument("--disable-dev-shm-usage") |
| 22 | +options.add_argument("--disable-features=VizDisplayCompositor") |
| 23 | +options.add_argument("--disable-features=NetworkService") |
| 24 | +driver = webdriver.Firefox(options=options) |
| 25 | +BASE_DIR = os.path.join(os.path.dirname(__file__), '..') |
| 26 | + |
| 27 | + |
| 28 | +def handler(request, jsonify): |
| 29 | + body = request.get_json() |
| 30 | + |
| 31 | + if body is None: |
| 32 | + return jsonify({'message': 'No body provided'}), 400 |
| 33 | + |
| 34 | + try: |
| 35 | + query = body['query'] |
| 36 | + scroll = body['scroll'] |
| 37 | + except Exception as e: |
| 38 | + return jsonify({'message': str(e) + " not provided"}), 400 |
| 39 | + |
| 40 | + query_url = urllib.parse.quote(query) |
| 41 | + print('Query URL: ', query_url) |
| 42 | + now = datetime.datetime.now() |
| 43 | + |
| 44 | + driver.get(f"https://www.youtube.com/results?search_query={query_url}") |
| 45 | + |
| 46 | + scroll_height = driver.execute_script("return window.innerHeight") |
| 47 | + video_links = [] |
| 48 | + video_titles = [] |
| 49 | + video_views = [] |
| 50 | + video_published_times = [] |
| 51 | + |
| 52 | + max_scroll = scroll |
| 53 | + file_name = f"{query}_scroll-{max_scroll}_{now.strftime('%Y%m%d_%H%M%S')}" |
| 54 | + |
| 55 | + # while True: |
| 56 | + while max_scroll > 0: |
| 57 | + print("Scroll:", max_scroll) |
| 58 | + max_scroll -= 1 |
| 59 | + video_ids = driver.find_elements(By.XPATH, "//a[@id='video-title']") |
| 60 | + print('video_ids: ', video_ids) |
| 61 | + |
| 62 | + for i, video_id in enumerate(video_ids): |
| 63 | + print("videoTitle", video_id.get_attribute("title")) |
| 64 | + print("videoID", video_id.get_attribute("href")) |
| 65 | + video_links.append(video_id.get_attribute("href")) |
| 66 | + video_titles.append(video_id.get_attribute("title")) |
| 67 | + |
| 68 | + video_infos = driver.find_elements( |
| 69 | + By.XPATH, "//span[@class='inline-metadata-item style-scope ytd-video-meta-block']") |
| 70 | + # print('video_infos: ', video_infos) |
| 71 | + |
| 72 | + for i, video_info in enumerate(video_infos): |
| 73 | + if "views" in video_info.text: |
| 74 | + view_count = video_info.text |
| 75 | + video_views.append(view_count) |
| 76 | + elif "ago" in video_info.text: |
| 77 | + published_time = video_info.text |
| 78 | + video_published_times.append(published_time) |
| 79 | + |
| 80 | + document_height_before = driver.execute_script( |
| 81 | + "return document.documentElement.scrollHeight") |
| 82 | + driver.execute_script( |
| 83 | + f"window.scrollTo(0, {document_height_before + scroll_height});") |
| 84 | + |
| 85 | + # write to file |
| 86 | + with open(f"{BASE_DIR}/results/{file_name}.txt", "a") as f: |
| 87 | + print(video_titles) |
| 88 | + for i, video_link in enumerate(video_links): |
| 89 | + print(video_link) |
| 90 | + # if i < len(video_links) - 1: |
| 91 | + # f.write( |
| 92 | + # f"{video_link} ‽ {video_titles[i]} ‽ {video_views[i]} ‽ {video_published_times[i]}\n") |
| 93 | + # else: |
| 94 | + # f.write( |
| 95 | + # f"{video_link} ‽ {video_titles[i]} ‽ {video_views[i]} ‽ {video_published_times[i]}") |
| 96 | + |
| 97 | + time.sleep(1.5) |
| 98 | + document_height_after = driver.execute_script( |
| 99 | + "return document.documentElement.scrollHeight") |
| 100 | + if document_height_after == document_height_before: |
| 101 | + break |
| 102 | + |
| 103 | + driver.quit() |
| 104 | + return jsonify({'message': 'success', "filename": file_name}), 200 |
0 commit comments