Как мне решить эту проблему
1 import discord 2 from discord.ext import commands 3 from selenium import webdriver 4 from selenium.webdriver.common.keys import Keys 5 6 chrome_options.add_experimental_option('debuggerAddress','127.0.0.1:9515') #set port 7 from selenium.webdriver.common.by import By 8 from selenium.webdriver.support.ui import WebDriverWait 9 from selenium.webdriver.support import expected_conditions as EC 10 from selenium.common.exceptions import TimeoutException 11 from selenium.common.exceptions import StaleElementReferenceException 12 from selenium.common.exceptions import MoveTargetOutOfBoundsException 13 from urllib.parse import urlparse 14 import re 15 import random 16 import requests 17 from bs4 import BeautifulSoup 18 import time 19 import os 20 import warnings 21 import json, base64 22 23 warnings.filterwarnings("ignore", category=DeprecationWarning) 24 25 PROXY = '138.197.162.125:8080' 26 chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None) 27 opts = webdriver.ChromeOptions() 28 opts.binary_location = chrome_bin 29 30 chrome_driver = r'C:\Users\ghattas\Desktop\chegg_bot-master' 31 opts.headless = True 32 opts.add_argument('--proxy-server=%s' % PROXY) 33 opts.add_argument("--no sandbox") 34 opts.add_argument("--disable-gpu") 35 36 37 def chrome_takeFullScreenshot(driver): 38 def send(cmd, params): 39 resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id 40 url = driver.command_executor._url + resource 41 body = json.dumps({'cmd': cmd, 'params': params}) 42 response = driver.command_executor._request('POST', url, body) 43 return response.get('value') 44 45 def evaluate(script): 46 response = send('Runtime.evaluate', {'returnByValue': True, 'expression': script}) 47 return response['result']['value'] 48 49 metrics = evaluate( \ 50 "({" + \ 51 "width: Math.max(window.innerWidth, document.body.scrollWidth, document.documentElement.scrollWidth)|0," + \ 52 "height: Math.max(innerHeight, document.body.scrollHeight, document.documentElement.scrollHeight)|0," + \ 53 "deviceScaleFactor: window.devicePixelRatio || 1," + \ 54 "mobile: typeof window.orientation !== 'undefined'" + \ 55 "})") 56 send('Emulation.setDeviceMetricsOverride', metrics) 57 screenshot = send('Page.captureScreenshot', {'format': 'png', 'fromSurface': True}) 58 send('Emulation.clearDeviceMetricsOverride', {}) 59 60 return base64.b64decode(screenshot['data']) 61 62 63 def virtual_click(browser, click_object, use_random=True): 64 try: 65 size = click_object.size 66 except StaleElementReferenceException: 67 print("StaleElementReferenceException") 68 return False 69 size_list = list(size.values()) 70 height = int(size_list[0]) - 1 71 width = int(size_list[1]) - 1 72 if use_random: 73 try: 74 height_rand = random.randint(1, height) 75 except ValueError: 76 height_rand = 1 77 try: 78 width_rand = random.randint(1, width) 79 except ValueError: 80 width_rand = 1 81 if not use_random: 82 height_rand = height 83 width_rand = width 84 action = webdriver.common.action_chains.ActionChains(browser) 85 try: 86 action.move_to_element_with_offset(click_object, width_rand, height_rand) 87 except StaleElementReferenceException: 88 return False 89 action.click() 90 try: 91 action.perform() 92 except MoveTargetOutOfBoundsException: 93 return False 94 except StaleElementReferenceException: 95 return False 96 return True 97 98 99 try: 100 os.mkdir('./screens') 101 except FileExistsError: 102 pass 103 104 request_queue = [] 105 flag = False 106 client = commands.Bot(command_prefix='!') 107 108 _2captcha_key = 'cb319d881ccd6998c30ae4a94c9cc666' 109 bot_token = 'NzY3MDU4ODQ4MDgyMTY1ODEw.X4sZOA.pFRc_rOn-9PiQ_YrDLlrk0FppuA' 110 111 112 @client.event 113 async def on_ready(): 114 print('Chegg-bot is ready! :D') 115 116 117 @client.command() 118 async def chegg(ctx, chegg_url): 119 global request_queue 120 global process_queue 121 global flag 122 123 """check if url is valid and whether the chegg site is working""" 124 if urlparse(chegg_url).hostname != 'www.chegg.com' or ctx.message.channel.name != "general":'767066491673640970' 125 await ctx.send(f'{ctx.author.mention} Invalid link. Please try again.') 126 return 127 else: 128 """confirmed that url domain is chegg and the channel is correct""" 129 request_object = {'user': ctx, 'url': chegg_url} 130 await ctx.send(f'{ctx.author.mention} Your request is in the queue. Please wait while it gets processed.') 131 if request_object not in request_queue: 132 time.sleep(random.uniform(2, 6)) 133 request_queue.append(request_object) 134 if not flag: 135 li = take_screenshot(request_object) 136 if li[0] == 0: 137 new_ctx = li[1] 138 await new_ctx.send(f'{new_ctx.author.mention} Invalid Chegg URL. Please check again.') 139 file_name, new_ctx = li 140 message = f'{new_ctx.author.mention} Be sure to click \'open original\' to view the full size image.\nLink: ' + chegg_url 141 fp = open('./screens/' + file_name, 'rb') 142 try: 143 await new_ctx.author.send(content=message, file=discord.File(fp)) 144 await new_ctx.send(content=f'{ctx.author.mention}Check your DMs!') 145 except: 146 await new_ctx.send( 147 content=f'{ctx.author.mention} Unable to send answer!\nEither your DMs aren\'t open or the request was too large!') 148 149 fp.close() 150 os.remove('./screens/' + file_name) # set your path to the screenshot 151 time.sleep(random.uniform(5, 8)) 152 if request_queue: 153 take_screenshot(request_queue[0]) 154 else: 155 return 156 157 158 ##hereeee 159 else: 160 await ctx.send(f'{ctx.author.mention} Unknown Error!') 161 return 162 163 164 def take_screenshot(r_obj): 165 global flag 166 flag = True 167 global request_queue 168 ctx = r_obj['user'] 169 url = r_obj['url'] 170 new_ctx = ctx 171 print(f'>>scraping for {ctx.author.name}-{url}') 172 """opens chegg question site""" 173 time.sleep(random.uniform(2, 4)) 174 browser.get(url) 175 time.sleep(random.uniform(9, 14)) 176 try: 177 test555 = browser.find_element_by_xpath('//*[@id="qna-body"]/main/section[1]/div/a') 178 virtual_click(browser, test555) 179 180 except: 181 pass 182 handle_captcha() 183 question_num_ptn = re.compile(r'-q\d+') 184 number = random.randint(10000000, 99999999) 185 file_name = 'screenshot' + str(number) + '.png' 186 png = chrome_takeFullScreenshot(browser) 187 188 with open("./screens/" + file_name, 'wb') as f: 189 f.write(png) 190 191 request_queue.remove(r_obj) 192 time.sleep(5) 193 browser.get('https://www.chegg.com') 194 flag = False 195 print('>>Saved screenshot') 196 197 return [file_name, new_ctx] 198 199 200 def handle_captcha(): # This isn't really needed in remote debugging non headless, but is essential elsewhere 201 if browser.title == 'Access to this page has been denied.': 202 print('>>A wild captcha appeared!!!!') 203 print(browser.find_element_by_tag_name('h1').text) 204 if browser.find_element_by_tag_name('h1').text == 'Please verify you are a human': 205 print('CAPTCHAAAAA!') 206 """captcha""" 207 html = browser.page_source 208 soup = BeautifulSoup(html, 'lxml') 209 sitekey = soup.find('div', attrs={'class': 'g-recaptcha'})['data-sitekey'] 210 data_2cap = {'key': _2captcha_key, 211 'method': 'userrecaptcha', 212 'googlekey': sitekey, 213 'pageurl': browser.current_url, 214 'invisible': '0', 215 'json': '0'} 216 r = requests.get( 217 f'https://2captcha.com/in.php?key={data_2cap["key"]}&method=userrecaptcha&googlekey={data_2cap["googlekey"]}&pageurl={data_2cap["pageurl"]}&invisible=1') 218 print(r.text) 219 id = r.text.split('|')[1] 220 callback = soup.find('div', attrs={'class': 'g-recaptcha'})['data-callback'] 221 r = requests.get(f'https://2captcha.com/res.php?key={data_2cap["key"]}&action=get&id={id}') 222 print(r.text) 223 status = r.text.split('|')[0] 224 i = 0 225 while status != 'OK': 226 print(f'{i}-Status is not OK, trying in 5 seconds-{status}') 227 r = requests.get(f'https://2captcha.com/res.php?key={data_2cap["key"]}&action=get&id={id}') 228 status = r.text.split('|')[0] 229 i += 1 230 time.sleep(random.uniform(2, 4)) 231 token_g = r.text.split('|')[1] 232 print(token_g) 233 js1 = f'document.getElementById("g-recaptcha-response").innerHTML="{token_g}";' 234 print(js1) 235 browser.execute_script(js1) 236 time.sleep(random.uniform(2, 3)) 237 js2 = f'{callback}("{token_g}");' 238 print(js2) 239 browser.execute_script(js2) 240 time.sleep(random.uniform(3, 5)) 241 242 243 def signin(): # Only use this function if you are using new instances of your browser each time 244 print('>>signing in!') 245 browser.get('https://www.chegg.com/auth?action=login&redirect=https%3A%2F%2Fwww.chegg.com%2F') 246 handle_captcha() 247 248 time.sleep(2) 249 email_elem = browser.find_element_by_id('emailForSignIn') 250 for character in 'alondra_calderon@ymail.com': 251 email_elem.send_keys(character) 252 time.sleep(0.1) 253 time.sleep(2) 254 255 password_elem = browser.find_element_by_id('passwordForSignIn') 256 for character in 'Blueyes97': 257 password_elem.send_keys(character) 258 time.sleep(0.1) 259 time.sleep(2) 260 261 browser.find_element_by_name('login').click() 262 263 try: 264 if WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[3]/div[2]/div[2]/div/div[3]/div/oc-component/div/div/div/div[2]/div[1]/div[1]/div/form/div/div/div/div/div[3]/span"))): 265 print('redirecting back to login') 266 browser.get('https://www.chegg.com/auth?action=login') 267 handle_captcha() 268 signin() 269 handle_captcha() 270 except TimeoutException: 271 pass 272 273 if browser.find_element_by_tag_name('h1').text == 'Oops, we\'re sorry!': 274 return [0] 275 handle_captcha() 276 277 278 if __name__ == '__main__': 279 browser = webdriver.Chrome(executable_path="chromedriver", options=opts) 280 signin() 281 client.run(bot_token) 282 # test comment
Что я уже пробовал:
у меня есть проблема в строке 124 я не знаю как ее исправить можете ли вы исправить ее для меня
ZurdoDev
Нет, потому что я не знаю, что такое линия 124 и в чем проблема.