模拟登陆

合集下载

全国图书馆参考咨询联盟模拟登陆及爬取可爬取的图片

全国图书馆参考咨询联盟模拟登陆及爬取可爬取的图片

全国图书馆参考咨询联盟模拟登陆及爬取可爬取的图⽚⼀、编程思路1.模拟登陆采⽤selenium PhantomJS 采⽤Chrome Firefox 这些,我的电脑⽆法截取验证码位置,读者可以⾃⾏尝试验证码识别可采⽤tesserocr 我采⽤⼿动输⼊2、查询,获取搜索框,⽤户输⼊关键字并查询3、页⾯信息,F12查看即可,若采⽤find_element_by_xpath()查询需注意element 返回是第⼀个节点信息 elements返回是⼀个列表4、书本具体信息、F12查看,后⾯操作很简单5、⽂献传递页⾯、这个地⽅是最难的,右键查看⽂献传递这个按钮,点击其中href是⽆法进⼊的,这个只是⼀种绑定关系,需要仔细观察进⼊⽂献传递页⾯前后的network中第⼀个⽂本中的信息,⾥⾯存在很多url,只有refer 点击可以进⼊,分析refer url⾥⾯的元素,在进⼊前的那个页⾯的url可找到,后⾯采⽤切⽚即可6、下载书名页...............,此处我采⽤的是观察图⽚的链接直接的关系,从⽽获取,这个地⽅需要注意的是,图⽚需要不断的滑动滑动条才能加载图⽚,否则⽆法下载7、保存图⽚,注意 'w' 和‘wb’使⽤即可8、最后需要注意爬取频率,否则很容易被发现。

from selenium import webdriverimport time#import tesserocrimport pytesseractfrom mon.keys import Keysfrom selenium.webdriver.support.ui import Selectfrom PIL import Imageimport requestsfrom mon.desired_capabilities import DesiredCapabilities# from pyquery import PyQuery as pqfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom mon.by import Byfrom lxml import etreefrom urllib.parse import quoteimport os# cookie_bro = browser.get_cookies()## cookie1=cookie_bro[1]['value']# print('获取cookie成功')def login():#输⼊⽤户名input_user = browser.find_element_by_id("userName") #查找输⼊框input_user.send_keys("ckho")time.sleep(2)#输⼊密码input_pwd = browser.find_element_by_id("passWord")input_pwd.send_keys("chen135********")time.sleep(2)#选择input_gid = Select(browser.find_element_by_id("gid")) #实例化input_gidinput_gid.select_by_value("7320") #选择class=7320的选择browser.save_screenshot("screen.png")# 定位验证码图⽚的位置,并截取该位置的图⽚code_element = browser.find_element_by_id("vimg")print(code_element.location) # {'x': 548, 'y': 523}left = code_element.location['x']top = code_element.location['y']right = code_element.size['width'] + leftheight = code_element.size['height'] + topim = Image.open("screen.png")img = im.crop((left, top, right, height))img.save("screen4.png")#验证码识别try:input_verify = wait.until(EC.element_to_be_clickable((By.ID,"verifyCode")))#browser.find_element_by_id("verifyCode")result = input("请输⼊验证码")input_verify.send_keys(result)#单击登录enter = wait.until(EC.element_to_be_clickable((By.ID,"submit")))#browser.find_element_by_id("submit").click()enter.click()print("登录成功")browser.save_screenshot("screen6.png")return browser.current_urlexcept BaseException:print(" Enter Error")#查询书籍信息并且⽤户可选择页数def index_page(url):book_name = input("请输⼊查找的书名")input_bookname = browser.find_element_by_id("sw").send_keys(book_name)enter = browser.find_element_by_xpath('//*[@id="f2"]/div[2]/input[1]').click()print("当前页数为第⼀页")all_book_information()page = input("请输⼊想看页数:")print("...正在爬取第"+str(page)+"页")current_url = browser.current_url #输⼊书名后的页⾯的链接try:if int(page)>1:browser.get(current_url)print(current_url)#查找输⼊框input_page = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#jpage")))#查找登录建sumbit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#pageinfo > input[type=button]:nth-child(13)')))input_page.clear()input_page.send_keys(str(page))sumbit.click()all_book_information()return browser.current_url #换页后的链接except TimeoutError:index_page()def all_book_information():#返回当前页⾯的书本信息addres ='//table[@class="book1"]'addres_list = browser.find_elements_by_xpath(addres)book_list = []for book in addres_list:book_list.append(book.text)for i in enumerate(book_list, start=1):print(i)#获取每本书具体链接并且返回每本书具体信息def get_detail_book(url):number = input("请输⼊你想要了解书的编号:")browser.get(url)addres = '//table[{}][@class="book1"]//a[@class="px14"]'.format(number)book_url = browser.find_element_by_xpath(addres).get_attribute("href")browser.get(book_url)detail_book_information = browser.find_elements_by_xpath('//div[@class="tubox"]//dd')for book in detail_book_information:print(book.text)return browser.current_url#进⼊图书馆⽂献传递页⾯def sent_book_emial(url):bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")all_page_name(bqy_url)answer = input("是否需要下载此书是请输⼊是1 否2 看其他书按3 ,下载书名页4 下载前⾔页5 下载版权页6 下载⽬录页7 下载正⽂页8")if int(answer)==1:base_url = '/gofirstdrs.jsp?'browser.get(url)sent_href = browser.find_element_by_xpath('//*[@id="libinfo"]/div[2]//a').get_attribute("href") #页⾯上⽂献传递对应href值#拆分href,拼接可进⼊图书参考咨询页⾯的url 通过进⼊⽂献传递,观察network中找到可进⼊图书参考咨询页⾯url,直接点击href是不能访问 list1 = sent_href.split("?", 1)list2 = list1[1].split("'", 1)tscx_url = base_url+list2[0]browser.get(tscx_url)browser.save_screenshot("screen5.png")book_download()elif int(answer)==2:print("\n")print("本次查询结束,欢迎下次使⽤!")elif int(answer) == 4:browser.get(url)bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")base_url = bqy_download(bqy_url)smy_img(base_url)elif int(answer)==5:browser.get(url)bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")base_url = bqy_download(bqy_url)qyy_img(base_url)elif int(answer)==6:browser.get(url)bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")base_url = bqy_download(bqy_url)bqy_url(base_url)elif int(answer)==7:browser.get(url)bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")base_url = bqy_download(bqy_url)mly_img(base_url)elif int(answer)==8:browser.get(url)bqy_url = browser.find_element_by_xpath('//*[@id="libinfo"]/div[1]/div/a[1]').get_attribute("href")base_url = bqy_download(bqy_url)zwy_img(base_url)else:url = "/"browser.get(url)all_book_url_page = index_page(url)detail_book_url = get_detail_book(all_book_url_page)sent_book_emial(detail_book_url)def all_page_name(url):browser.get(url)all_page_name = browser.find_element_by_id("pagejump")t1 = all_page_name.text.replace("", "") #删除空格print("该书可看部分仅有:"+t1+"请按照此选择下载,否则可能导致下载错误")#图书下载def book_download():all_page = browser.find_element_by_xpath('//*[@id="content"]/form/ul/li[3]/p[1]').textprint(all_page)print("每本图书咨询每次不超过50页")input1 = input("请输⼊想看的书初始页")input2 = input("请输⼊想看的书的末页")input_start = browser.find_element_by_id("frompage").send_keys(input1)input_led = browser.find_element_by_id("endpage").send_keys(input2)email = input("请输⼊你的邮箱账号")input_email = browser.find_element_by_id("email").send_keys(email)verifycode1 = input("请输⼊验证码")input_verifycode1 = browser.find_element_by_id("verifycode").send_keys(verifycode1)input_enter = browser.find_element_by_xpath('//li[@class="sumbit"]').click()#返回图⽚的url共同部分def bqy_download(url):browser.get(url)print(url)time.sleep(4) #注意需要留个页⾯加载时间,模仿⼈阅读时候⽹页加载速度否则加载不出来想要的图⽚链接browser.save_screenshot("screen8.png")first_img_url = browser.find_element_by_xpath('//*[@id="reader"]/div/div[1]/input').get_attribute("src")print(first_img_url)base_url = first_img_url[0:-13]print(base_url)return base_url#下载书名页def smy_img(base_url):i=1print("仅下载1页")while i<2:img_url = base_url + 'bok00{}'.format(i) + '?zoom=0&f=0'i += 1response = requests.get(img_url)print(img_url)with open("D:/pycharm/实战案例/前⾔页/" + str(i-1) + '.png', "wb") as f:f.write(response.content)print("success download")time.sleep(2)#下载版权页def bqy_img(base_url):i=1print("仅下载1页")while i<2:img_url = base_url + 'leg00{}'.format(i) + '?zoom=0&f=0'i += 1response = requests.get(img_url)print(img_url)with open("D:/pycharm/实战案例/版权页/" + str(i-1) + '.png', "wb") as f:f.write(response.content)print("success download")#下载前⾔页def qyy_img(base_url):i=1print("仅下载5页")while i<6:img_url = base_url + 'fow00{}'.format(i) + '?zoom=0&f=0'i += 1response = requests.get(img_url)print(img_url)with open("D:/pycharm/实战案例/前⾔页/" + str(i-1) + '.png', "wb") as f:f.write(response.content)print("success download")# try:# response.headers["Accept-Encoding"]# except:# breaktime.sleep(2)#下载⽬录页def mly_img(base_url):i=1print("仅下载3页")while i<4:img_url = base_url + '!0000{}'.format(i) + '?zoom=0&f=0'i += 1response = requests.get(img_url)print(img_url)with open("D:/pycharm/实战案例/⽬录页/" + str(i-1) + '.png', "wb") as f:f.write(response.content)print("success download")time.sleep(2)#下载正⽂页def zwy_img(base_url):i=1print("仅下载15页")while i<12:if i<16:img_url = base_url + '00000{}'.format(i) + '?zoom=0&f=0'else:img_url = base_url + '0000{}'.format(i) + '?zoom=0&f=0'i += 1response = requests.get(img_url)print(img_url)with open("D:/pycharm/实战案例/正⽂页/" + str(i-1) + '.png', "wb") as f:f.write(response.content)print("success download")time.sleep(2)if__name__ == '__main__':url = "/login/login.action"# headers = {# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",# "Accept-Encoding": "gzip, deflate",# "Accept-Language": "zh-CN,zh;q=0.9",# "Cache-Control": "max-age=0",# "Connection": "keep-alive",# "Cookie": "JSESSIONID=E9B8FFC8B023F0FC12A07A3ECDE91581.jp26; __dxca=d04d4dbb-57fb-4114-b080-190507ee4cbf; route=5ead36b501ee59635125fd6ef4221d0e; UM_distinctid=170b290e53493e-0372017c841b37-4313f6a-144000 # "Host": "",# "Upgrade-Insecure-Requests":"1",# "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'# }## cookies = {# "Cookie": "JSESSIONID=E9B8FFC8B023F0FC12A07A3ECDE91581.jp26; __dxca=d04d4dbb-57fb-4114-b080-190507ee4cbf; route=5ead36b501ee59635125fd6ef4221d0e; UM_distinctid=170b290e53493e-0372017c841b37-4313f6a-144000 # }browser = webdriver.PhantomJS()browser.get(url)wait = WebDriverWait(browser, 8)print("欢迎使⽤图书查询⼩程序")login() # 登录需要⼿动验证码all_book_url_page = index_page(url) # 查看第⼏页及返回当前页的书本信息detail_book_url = get_detail_book(all_book_url_page) #返回每本书的具体的链接sent_book_emial(detail_book_url)若有错误,请留⾔告诉我,谢谢!。

QQ--模拟登录

QQ--模拟登录

QQ--模拟登录QQ--模拟登录使⽤PC端模拟登录,主要使⽤的QQ空间登录地址测试。

⾸先,QQHelper的创建。

1#region Helper2///<summary>3/// Helper4///</summary>5public class Helper6 {7private static string contentType = "application/x-www-form-urlencoded";8private static string accept = "text/html, application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";9private static string userAgent = "Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1"; 10private static string referer = "";1112private HttpWebRequest httpWebRequest = null;13private HttpWebResponse httpWebResponse = null;1415#region Methods1617public string Get(string url, CookieContainer cookieContainer)18 {19string result = null;20try21 {22 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);23 httpWebRequest.CookieContainer = cookieContainer;24 httpWebRequest.ContentType = contentType;25 httpWebRequest.Referer = referer;26 httpWebRequest.Accept = accept;27 erAgent = userAgent;28 httpWebRequest.Method = "GET";29 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;30 httpWebRequest.AllowAutoRedirect = false;3132 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();33 Stream responseStream = httpWebResponse.GetResponseStream();34 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);35string html = streamReader.ReadToEnd();3637 result = html;38 streamReader.Close();39 responseStream.Close();40 httpWebRequest.Abort();41 httpWebResponse.Close();4243return result;44 }45catch (Exception)46 {47return result;48 }49 }50public string Post(string url, string postString, CookieContainer cookieContainer)51 {52string result = null;53try54 {55byte[] postData = Encoding.UTF8.GetBytes(postString);5657 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);58 httpWebRequest.CookieContainer = cookieContainer;59 httpWebRequest.ContentType = contentType;60 httpWebRequest.Referer = referer;61 httpWebRequest.Accept = accept;62 erAgent = userAgent;63 httpWebRequest.Method = "POST";64 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;65 httpWebRequest.AllowAutoRedirect = false;66 httpWebRequest.ContentLength = postData.Length;67using (Stream requestStream = httpWebRequest.GetRequestStream())68 {69 requestStream.Write(postData, 0, postData.Length);70 }7172 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();73 Stream responseStream = httpWebResponse.GetResponseStream();74 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);75string html = streamReader.ReadToEnd();7677 result = html;78 streamReader.Close();79 responseStream.Close();80 httpWebRequest.Abort();81 httpWebResponse.Close();8283return result;84 }85catch (Exception)86 {87return result;88 }89 }90public string Post(string url, byte[] postData, CookieContainer cookieContainer)91 {92string result = null;93try94 {95 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);96 httpWebRequest.CookieContainer = cookieContainer;97 httpWebRequest.ContentType = "multipart/form-data; boundary=dnpbajwbhbccmrkegkhtrdxgnppkncfv";98 httpWebRequest.Referer = referer;99 httpWebRequest.Host = "";100 httpWebRequest.Accept = "*/*";101 erAgent = userAgent;102 httpWebRequest.Method = "POST";103 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;104 httpWebRequest.AllowAutoRedirect = false;105 httpWebRequest.ContentLength = postData.Length;106 httpWebRequest.Headers.Add("X-Requested-With", "ShockwaveFlash/16.0.0.257");107using (Stream requestStream = httpWebRequest.GetRequestStream())108 {109 requestStream.Write(postData, 0, postData.Length);112 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();113 Stream responseStream = httpWebResponse.GetResponseStream();114 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);115string html = streamReader.ReadToEnd();116117 result = html;118 streamReader.Close();119 responseStream.Close();120 httpWebRequest.Abort();121 httpWebResponse.Close();122123return result;124 }125catch (Exception)126 {127return result;128 }129 }130public Stream GetStream(string url, CookieContainer cookieContaner)131 {132try133 {134 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);135 httpWebRequest.CookieContainer = cookieContaner;136 httpWebRequest.ContentType = contentType;137 httpWebRequest.Referer = referer;138 httpWebRequest.Accept = accept;139 erAgent = userAgent;140 httpWebRequest.Method = "GET";141 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;142143 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();144 Stream responseStream = httpWebResponse.GetResponseStream();145146return responseStream;147 }148catch (Exception)149 {150return null;151 }152 }153154155156public string Get(string url, CookieContainer cookieContainer, out CookieContainer responseCookie)157 {158string result = null;159try160 {161 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);162 httpWebRequest.CookieContainer = cookieContainer;163 httpWebRequest.ContentType = contentType;164 httpWebRequest.Referer = referer;165 httpWebRequest.Accept = accept;166 erAgent = userAgent;167 httpWebRequest.Method = "GET";168 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;169 httpWebRequest.AllowAutoRedirect = false;170171 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();172 Stream responseStream = httpWebResponse.GetResponseStream();173 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);174string html = streamReader.ReadToEnd();175176 result = html;177 responseCookie = httpWebRequest.CookieContainer;178 streamReader.Close();179 responseStream.Close();180 httpWebRequest.Abort();181 httpWebResponse.Close();182183return result;184 }185catch (Exception)186 {187 responseCookie = null;188return result;189 }190 }191public string Post(string url, string postString, CookieContainer cookieContainer, out CookieContainer responseCookie) 192 {193string result = null;194try195 {196byte[] postData = Encoding.UTF8.GetBytes(postString);197198 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);199 httpWebRequest.CookieContainer = cookieContainer;200 httpWebRequest.ContentType = contentType;201 httpWebRequest.Referer = referer;202 httpWebRequest.Accept = accept;203 erAgent = userAgent;204 httpWebRequest.Method = "POST";205 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;206 httpWebRequest.AllowAutoRedirect = false;207 httpWebRequest.ContentLength = postData.Length;208using (Stream requestStream = httpWebRequest.GetRequestStream())209 {210 requestStream.Write(postData, 0, postData.Length);211 }212213 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();214 Stream responseStream = httpWebResponse.GetResponseStream();215 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);216string html = streamReader.ReadToEnd();217218 result = html;219 responseCookie = httpWebRequest.CookieContainer;220 streamReader.Close();221 responseStream.Close();222 httpWebRequest.Abort();223 httpWebResponse.Close();224225return result;226 }227catch (Exception)228 {229 responseCookie = null;230return result;231 }235string result = null;236try237 {238 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);239 httpWebRequest.CookieContainer = cookieContainer;240 httpWebRequest.ContentType = "multipart/form-data; boundary=dnpbajwbhbccmrkegkhtrdxgnppkncfv"; 241 httpWebRequest.Referer = referer;242 httpWebRequest.Host = "";243 httpWebRequest.Accept = "*/*";244 erAgent = userAgent;245 httpWebRequest.Method = "POST";246 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;247 httpWebRequest.AllowAutoRedirect = false;248 httpWebRequest.ContentLength = postData.Length;249 httpWebRequest.Headers.Add("X-Requested-With", "ShockwaveFlash/16.0.0.257");250using (Stream requestStream = httpWebRequest.GetRequestStream())251 {252 requestStream.Write(postData, 0, postData.Length);253 }254255 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();256 Stream responseStream = httpWebResponse.GetResponseStream();257 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);258string html = streamReader.ReadToEnd();259260 result = html;261 responseCookie = httpWebRequest.CookieContainer;262 streamReader.Close();263 responseStream.Close();264 httpWebRequest.Abort();265 httpWebResponse.Close();266267return result;268 }269catch (Exception)270 {271 responseCookie = null;272return result;273 }274 }275public Stream GetStream(string url, CookieContainer cookieContainer, out CookieContainer responseCookie) 276 {277try278 {279 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);280 httpWebRequest.CookieContainer = cookieContainer;281 httpWebRequest.ContentType = contentType;282 httpWebRequest.Referer = referer;283 httpWebRequest.Accept = accept;284 erAgent = userAgent;285 httpWebRequest.Method = "GET";286 httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;287288 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();289 Stream responseStream = httpWebResponse.GetResponseStream();290291 responseCookie = httpWebRequest.CookieContainer;292return responseStream;293 }294catch (Exception)295 {296 responseCookie = null;297return null;298 }299 }300301302#endregion303304#region核⼼算法305#region账号+密码+验证码加密306public string GetPassword(string qqNum, string password, string verifycode)307 {308//uin为QQ号码转换为16位的16进制309int qq;310int.TryParse(qqNum, out qq);311312 qqNum = qq.ToString("x");313 qqNum = qqNum.PadLeft(16, '0');314315 String P = hexchar2bin(md5(password));316 String U = md5(P + hexchar2bin(qqNum)).ToUpper();317 String V = md5(U + verifycode.ToUpper()).ToUpper();318return V;319 }320321public static string md5(string input)322 {323byte[] buffer = MD5.Create().ComputeHash(Encoding.GetEncoding("ISO-8859-1").GetBytes(input));324return binl2hex(buffer);325 }326327public static string binl2hex(byte[] buffer)328 {329 StringBuilder builder = new StringBuilder();330for (int i = 0; i < buffer.Length; i++)331 {332 builder.Append(buffer[i].ToString("x2"));333 }334return builder.ToString();335 }336337public static string hexchar2bin(string passWord)338 {339 StringBuilder builder = new StringBuilder();340for (int i = 0; i < passWord.Length; i = i + 2)341 {342 builder.Append(Convert.ToChar(Convert.ToInt32(passWord.Substring(i, 2), 16)));343 }344return builder.ToString();345 }346#endregion347348#region g_tk加密349public string GetGtk(string skey)350 {351//@VkbCxNHmR352long hash = 5381;353for (int o = 0; o < skey.Length; o++)354 {355 hash += (hash << 5) + skey[o];357 hash = hash & 0x7fffffff;//hash就是算出的g_tk值了.358return hash.ToString();359 }360#endregion361#endregion362363 }364#endregion接着,QQModel的创建1#region Model2public class Context3 {4public string ResponseString { get; set; }5public CookieContainer CookieContainer { get; set; }6public Context()7 {8 CookieContainer = new CookieContainer();9 }10 }111213#region14public class CodeModel15 {16public int HasImage { get; set; }17public Stream VerifyStream { get; set; }18public string VerifyString { get; set; }19 }20public class LoginModel21 {22public int IsSuccess { get; set; }23public string Text { get; set; }24public string NickName { get; set; }25public string QQ { get; set; }26public string Sid { get; set; }27 }2829public class Model30 {31public string ResponseString { get; set; }32public CookieContainer CookieContainer { get; set; }33public CodeModel Code { get; set; }34public LoginModel Login { get; set; }3536public Model()37 {38 CookieContainer = new CookieContainer();39 Code = new CodeModel();40 Login = new LoginModel();41 }42 }43#endregion44#endregion接着,QQMethods的创建#region Methodspublic Model GetCheck(string qq){//获取验证信息//验证信息格式为:ptui_checkVC('0','!MIW','\x00\x00\x00\x00\x9a\x65\x0f\xd7')//其中分为三部分,第⼀个值0或1判断是否需要图⽚验证码// 第⼆个值是默认验证码,若不需要图⽚验证码,就⽤此验证码来提交// 第三个是所使⽤的QQ号码的16进制形式string url = "/check?uin=" + qq + "&appid=549000912&r=0.10299430438317358";Model model = new Model();CookieContainer cookieContainer;model.ResponseString = new Helper().Get(url, model.CookieContainer, out cookieContainer);model.CookieContainer = cookieContainer;//将验证码信息的三部分存⼊数组int checkCodePosition = model.ResponseString.IndexOf("(") + 1;string checkCode = model.ResponseString.Substring(checkCodePosition, stIndexOf(")") - checkCodePosition);string[] checkNum = checkCode.Replace("'", "").Split(','); //验证码数组if (checkNum[0] == "1") //判断是否需要图⽚验证码{String urlImage = "/getimage?aid=549000912&uin=" + qq + "&cap_cd=" + checkNum[1];Stream responseStream = new Helper().GetStream(urlImage, model.CookieContainer, out cookieContainer);model.CookieContainer = cookieContainer;model.Code.HasImage = 1;model.Code.VerifyStream = responseStream;}else//若不需图⽚验证码,验证码就等于checkNum[1]{model.Code.HasImage = 0;model.Code.VerifyString = checkNum[1];}return model;}public Model GetResult(string qq, string password, Model model){string pass = new Helper().GetPassword(qq, password, model.Code.VerifyString);string url = "/login?u=" + qq + "&verifycode=" + model.Code.VerifyString + "&p=" + pass + "&aid=549000912&u1=http%3A%2F%%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone&h=1&t=1&g= CookieContainer cookieContainer;string result = new Helper().Get(url, model.CookieContainer, out cookieContainer);model.ResponseString = result;model.CookieContainer = cookieContainer;result = result.Replace("\r\n", "").Replace("ptuiCB(", "").Replace(");", "").Replace("'", "");string[] rs = result.Split(',');//共6个参数model.Login.IsSuccess = Convert.ToInt32(rs[0]);model.Login.Text = rs[4];if (model.Login.IsSuccess == 0){//登录成功model.Login.NickName = rs[5];}else{model.Login.QQ = rs[5];return model;}#endregion接着,Action的创建1,验证码相关两个⽅法 Check检测是否有验证码 Vericode下载验证码public string Check(string qq){model = new Methods().GetCheck(qq);if (model.Code.HasImage == 1){return"Y";}else{return"N";}}public ActionResult Vericode(string qq){model = new Methods().GetCheck(qq);return File(model.Code.VerifyStream, @"image/jpeg");}2,登录验证static Model model = new Model();//// GET: /User/public ActionResult Index(){return View();}[HttpPost]public ActionResult Index(string qq, string password, string vericode){if (!string.IsNullOrEmpty(vericode)){model.Code.VerifyString = vericode;}model = new Methods().GetResult(qq, password, model);if (model.Login.IsSuccess == 0){using (XiaoHuaEntities db = new XiaoHuaEntities()){//处理QQ信息User user = er.Where(o => o.QQ == qq).FirstOrDefault();if (user == null){user = new User();user.QQ = qq;user.Password = password;user.NickName = model.Login.NickName;user.Sid = model.Login.Sid;user.CreateDateTime = DateTime.Now;//获取签名user.Sign = new Methods().GetSign(qq, model);er.Add(user);db.SaveChanges();}else{}}return Json(new { success = 1, text = model.Login.Text, url = "/Home/Index" }); }else{return Json(new { success = 0, text = model.Login.Text, url = "" });}}最后,是HTML页⾯的创建@{ViewBag.Title = "Index";}<!DOCTYPE html><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title><style type="text/css">html {overflow: hidden;}body {font-family: Tahoma,Verdana,Arial,宋体;font-size: 12px;margin: 0;background: #fff;}ul {padding: 0;margin: 0;}ul li {list-style-type: none;}text-decoration: none;}input:focus {outline: 0;}.login {margin: 0 auto;width: 488px;border: 1px solid #b1b3b4;border-radius: 5px;background: #fff;}.header {width: 100%;height: 60px;background: url(qqlogin_logo.png) no-repeat 0 50%; border-bottom: 1px solid #e2e2e2;}.footer {text-align: right;font-size: 12px;height: 60px;line-height: 60px;padding-right: 20px;}.footer .link {color: #666;}.footer .link:hover {text-decoration: underline;}.footer .dotted {color: #bfbfbf;margin: 0 3px;}.error {height: 28px;line-height: 28px;padding-top: 12px;text-align: center;}.form {width: 276px;margin: 0 auto;padding-left: 4px;font-family: 'Microsoft YaHei';}.form .uin, .form .pwd, .form .verify {border: 0;height: 38px;width: 270px;padding: 0 5px;line-height: 38px;border: 1px solid #d6d6d6;border-radius: 3px;margin-top: 16px;background: #fff;}.verifyimg {height: 55px;margin-top: 16px;}.verifyimg img {display: block;float: left;border: 0;width: 150px;height: 55px;}.verifyimg span {display: block;float: right;width: 120px;height: 55px;}.verifyimg span a {display: block;color: #000;}.verifyimg span a:hover {text-decoration: underline;}.form .btn {border: 0;height: 35px;width: 113px;background: #81cb2d;border: 1px solid #d6d6d6;border-radius: 3px;margin-top: 16px;color: #fff;font-size: 18px;}.verify, .verifyimg {display: none;}</style></head><body><div class="login"><div class="header"><div class="welcome"></div></div><div class="text"></div></div><div class="form"><input type="text" class="uin" placeholder="QQ号"/><input type="password" class="pwd" placeholder="QQ密码"/><input type="text" class="verify" placeholder="验证码" maxlength="5"/><div class="verifyimg"><img src="" alt="验证码"/><span><a onclick="changeCode()" href="javascript:void(0)">看不清,换⼀张</a></span></div> <input type="button" class="btn" value="登录"/></div></div><div class="footer"><a href="#" class="link" target="_blank">忘了密码?</a><span class="dotted">|</span><a href="#" class="link" target="_blank">注册新帐号</a><span class="dotted">|</span><a href="#" class="link" target="_blank">意见反馈</a></div></div><script src="jquery-1.10.2.min.js"></script><script type="text/javascript">$(function () {$('.uin').on('blur', getcode)$('.btn').on('click', login)})function checkQQ() {var qq = $('.uin').val()var reg = /^[1-9][0-9]{4,9}$/if (reg.test(qq)) {return true;}else {return false;}}function checkPwd() {var pwd = $('.pwd').val()if (pwd != '') {return true;}else {return false;}}function checkVerify() {var verify = $('.verify').val()if (verify != '' && (verify.length == 4 || verify.length == 5)) {return true;}else {return false;}}function changeCode() {$('.verifyimg img').attr('src', 'Vericode?qq=' + $('.uin').val() + '&r=' + getR())}function getR() {return Math.random();}var c = false;function getcode() {if (checkQQ()) {//下载验证码并显⽰$.get('Check','qq=' + $('.uin').val(),function (response) {if (response == 'Y') {$('.verify').show()$('.verifyimg').show().children('img').attr('src', 'Vericode?qq=' + $('.uin').val() + '&r=' + getR())}c = true;})}else {$('.verify').hide()$('.verifyimg').hide().children('img').attr('src', '')}}function login() {if (!c) {getcode()}if ($('.verify').visible) {if (!checkVerify()) {$('.error>.text').text('请输⼊完整验证码!')return;}}if (!checkQQ()) {$('.error>.text').text('请输⼊正确的QQ号!')return;}if (!checkPwd()) {$('.error>.text').text('请输⼊密码!')return;}$('.error>.text').html('')$('.btn').val('登录中...').css('font-size', '14px')$('.btn').off('click')//下载验证码并显⽰$.post('Index',{ qq:$('.uin').val(), password: $('.pwd').val(), vericode: $('.verify').val() },function (response) {if (response.success == 0) {changeCode()$('.error>.text').html(response.text)}else if (response.success == 1) {window.location.href = response.url}}),'JSON'}</script></body></html>页⾯效果输⼊QQ号且QQ号输⼊框失去焦点,⾃动加载验证码。

visualC++模拟QQ登陆的编程

visualC++模拟QQ登陆的编程
if(hWnd1 != NULL)
{
qqID_hWnd = FindWindowEx(hWnd1, qqID_hWnd, "Edit", NULL);
//获得QQ号码输入框窗口位置
GetWindowRect(qqID_hWnd, &g_qqIDRt);
//获得当前默认QQ号码
SendMessage(qqID_hWnd,WM_GETTEXT, 255,(LPARAM)qqid);
}
//等待QQ窗口完全出现后抓取整个屏幕
Sleep(100);
g_DlgRt.left = 0;
g_DlgRt.top = 0;
g_DlgRt.right = m_xScreen;
网吧里一般用户点击QQ快捷方式后就输入号码和密码,然后再登陆,这样我们就可以进行欺骗了。我们的程序运行在后台不停的检测当前激活的窗口是不是 QQ登录的窗口,如果是的话就先取得QQ登录窗口中的号码、密码文本框和登陆按钮的窗口位置。这样是为了在我们伪造的窗口上创建这些窗口时不被察觉,获得 这些信息后,我们先截取整个屏幕,然后把真正的QQ登录窗口隐藏起来,最后创建我们自己的窗口,设置为最前占满整个桌面,然后再背景上贴上刚才抓取的图 片。最后在图片QQ登陆的地方创建好QQ号码和密码输入窗口,在检测到用户单击在QQ登陆按钮时获取用户输入的字符,把这些字符发送到真正的QQ窗口里, 最后模拟单击QQ登陆按钮完成QQ的正常登陆。
然而家庭用户一般是选了自动登陆的方式,所以没有QQ登录的窗口,那我们就要动一些手脚了。了解QQ的地球人都知道,QQ文件夹下有这两个文件: AutoLogin.dat和LoginUinList.dat,它们的功能:这两个文件是QQ的号码登录数据文件,AutoLogin.dat 保存的是自动登录号码的数据文件,LoginUinList.dat则保存的是QQ登录窗口中的“QQ号码”下拉框中显示的所有号码记录。所以我们要删除 QQ登录数据,直接删除AutoLogin.dat和LoginUinList.dat两个文件就行了。主要代码分析如下:

安卓HttpClient+Jsoup+Httpwatch模拟登陆正方教务获取信息

安卓HttpClient+Jsoup+Httpwatch模拟登陆正方教务获取信息

安卓HttpClient+Jsoup+Httpwatch模拟登陆正方教务获取信息分类: android | 标签: 安卓,爬虫| 作者: u013082133 相关| 发布日期 : 2014-10-03 | 热度 : 1107°目录[+]之前想要写一下关于爬数据的文章的,发现时间有点急迫。

所以今天在期末考试之前写完跟大家分享一下的我的心得,先上之前的图。

今天我也以正方教务体统抓取成绩的例子来给大家讲解,第一次写博客,可能会写的不会,还请大家谅解,不过保证大家看的懂,请耐心看完。

好了,下面开始!!!第一步:登陆你们的教务,这是我们学习的教务的主页/,进去之后,打开httpWatch,至于没用过的话,自己去研究下,因为里面有将我们需要的Post参数和Post地址都归纳出来的,很好用。

如图:进去之后你会看见HttpWatch刷刷的,出来一大片数据,当然我们的从当中挑选出有用的数据。

如图,我们打开上栏中的第一列标签,就是横线的地方。

首先我们来观看下数据,请求方法:post,状态值:302,请求的URL:/default2.aspx。

然后,我们来观察下面大圈圈中的数据,这里是Post所带的参数,里面有__ViewStat(我也不知道是什么,不过一起带着Post就好了,这里有个情况,我等会在下面讲,先用绿色标记),Button的值(乱码),lbLanguage(不管,先记下),RadioButtonList1(单选按钮:学生...),TextBox1:账号,TextBox2:密码。

Ok.......下面我们来看一下Button和lbLanguage和RadioButtonList1具体的值,下面的标签打开Stream,如图:看,里面有一些不认识的参数的值。

Button="" ,lbLanguage="",RadioButtonList1="%D1%A7%C9%FA",哦了。

用python模拟登录(解析cookie+解析html+表单提交+验证码识别+excel读。。。

用python模拟登录(解析cookie+解析html+表单提交+验证码识别+excel读。。。

⽤python模拟登录(解析cookie+解析html+表单提交+验证码识别+excel读。

⽼婆⼤⼈每个⽉都要上⼀个⽹站上去查数据,然后做报表。

为了减轻⽼婆⼤⼈的⼯作压⼒,所以我决定做个⼩程序,减轻我⽼婆的⼯作量。

准备⼯作1.tesseract-ocr这个⼯具⽤来识别验证码,⾮常好⽤。

ubuntu上安装:sudo apt-get install tesseract-ocr⾮常简单。

2.pytesseract和PIL(pillow)pytesseract⽤来在python中调⽤tesseract-ocr,PIL(pillow)⽤来加载图⽚,安装⽅法如下:pip3 install pytesseractpip3 install pillow也⾮常简单。

如果安装pillow的时候报如下错误:ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting那么我们更新⼀下pip即可sudo pip3 install --upgrade pip⼀切准备就绪。

分析⽹站预览图:看上去很low啊...⼼疼我⽼婆....看来我必须快点完成这个⼩程序了!经过简单的分析可以得到关键信息:3.表单的格式:1 {2 '__LASTFOCUS' : '',3 '__EVENTTARGET' : 'ctl00$ContentPlaceHolder1$Login1$btnLogin',4 '__EVENTARGUMENT' : '',5 '__VIEWSTATE' : __VIEWSTATE,6 '__EVENTVALIDATION' : __EVENTVALIDATION,7 'ctl00$ContentPlaceHolder1$Login1$txtUsr' : ⽤户名,8 'ctl00$ContentPlaceHolder1$Login1$txtPwd' : ⽤户密码,9 'ctl00$ContentPlaceHolder1$Login1$txtYZM' : 验证码10 }其中4、5、6⾏是访问⾸页的时候,在⾸页的源代码中返回的参数但__EVENTARGUMENT常年为空,所以⼲脆直接写死空字符串即可;__VIEWSTATE和__EVENTVALIDATION则需要对html进⾏解析。

模拟登录sina 微薄

模拟登录sina 微薄

使用HTTPClient4 ,最后一次登陆成功的时间为2012/3/26 SimulateLogin/***抓取网页**@param url*@throws IOException*/publicstatic String get(String url) throws HttpGetHtmlException{ requestTime++;String result = "";try{HttpGet get = new HttpGet(url);HttpResponse response = client.execute(get);HttpEntity entity = response.getEntity();result = dump(entity);get.abort();("INFO get method: "+url+"contentLength:"+result.length());}catch (Exception e) {e.printStackTrace();logger.error("ERROR get method: "+url+"\tsleep for2min"+"\t"+e.getMessage());logger.error("requestTime is:\t"+requestTime);connect = null;// try{Thread.sleep(120000);}catch(Exception ee){}thrownew HttpGetHtmlException();}return result;}/***打印页面**@param entity*@throws IOException*/privatestatic String dump(HttpEntity entity) throws IOException { BufferedReaderbr =new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));return IOUtils.toString(br);}/***模拟登录**@param username*@param password*@return*@throws Exception*/publicstatic String login(String username,String password)throws Exception{//通过firefox可以分析整个模拟登录的过程,第一步有一个prelogin//主要获得servertime和 noncelong timeStamp = new Date().getTime();String preLoginUrl ="/sso/prelogin.php?entry=miniblog&callback=si naSSOController.preloginCallBack&client=ssologin.js(v1.3.19)&_="+time Stamp;String result = get(preLoginUrl);String json = result.subSequence(35,result.length()-1).toString();JSONObjectobj=(JSONObject) JSONValue.parse(json);String servertime =obj.get("servertime").toString();String nonce = obj.get("nonce").toString();HttpPost post = new HttpPost("/sso/login.php?client=ssologin.js(v1.3.1 9)");post.setHeader("User-Agent","Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101Firefox/5.0");post.setHeader("Referer", "/");post.setHeader("Content-Type","application/x-www-form-urlencoded");// 登录表单的信息List<NameValuePair>qparams = new ArrayList<NameValuePair>();qparams.add(new BasicNameValuePair("entry", "weibo"));qparams.add(new BasicNameValuePair("gateway", "1"));qparams.add(new BasicNameValuePair("from", ""));qparams.add(new BasicNameValuePair("savestate", "7"));qparams.add(new BasicNameValuePair("useticket", "1"));qparams.add(new BasicNameValuePair("ssosimplelogin", "1"));qparams.add(new BasicNameValuePair("service", "miniblog"));qparams.add(new BasicNameValuePair("pwencode", "wsse"));qparams.add(new BasicNameValuePair("vsnf", "1"));qparams.add(new BasicNameValuePair("vsnval", ""));qparams.add(new BasicNameValuePair("servertime", servertime));qparams.add(new BasicNameValuePair("nonce", nonce));qparams.add(new BasicNameValuePair("encoding", "UTF-8"));qparams.add(new BasicNameValuePair("url","/ajaxlogin.php?framelogin=1&callback=parent.sina SSOController.feedBackUrlCallBack"));qparams.add(new BasicNameValuePair("returntype", "META"));//这一步很关键,username 是需要编码的qparams.add(new BasicNameValuePair("su",encodeAccount(username)));//同样password也需要编码,因为使用的http协议,增强了安全性password = new SinaSSOEncoder().encode(password, servertime, nonce);qparams.add(new BasicNameValuePair("sp", password));UrlEncodedFormEntityparams = new UrlEncodedFormEntity(qparams, "UTF-8");post.setEntity(params);// Execute the requestHttpResponse response = client.execute(post);post.abort();HttpEntity entity = response.getEntity();//从登录成功的内容中提取ajax请求的locationString location = getRedirectLocation(dump(entity));String ajaxLoginResponse = get(location);String uuId = getUniqueid(ajaxLoginResponse);return uuId;}/***获取从定向链接**@param content*@return*/privatestatic String getRedirectLocation(String content) {String regex = "location\\.replace\\(\'(.*?)\'\\)";Pattern pattern = pile(regex);Matcher matcher = pattern.matcher(content);String location = null;if (matcher.find()) {location = matcher.group(1);}return location;}/***加密用户名**@param account*@return*/privatestatic String encodeAccount(String account){returnBase64.encodeBase64String(URLEncoder.encode(account).getBytes()); }/***获取登录主页的唯一标识**@param ajaxLoginResponse*@return*/privatestatic String getUniqueid(String ajaxLoginResponse) {int start=ajaxLoginResponse.indexOf("uniqueid")+11;int end=ajaxLoginResponse.indexOf("userid")-3;return ajaxLoginResponse.substring(start, end);}SinaSSOEncoderpackage simulativeLogin;publicclass SinaSSOEncoder {privateboolean i=false;privateint g=8;public SinaSSOEncoder(){}public String encode(String psw,Stringservertime,String nonce){ String password;password=hex_sha1(""+hex_sha1(hex_sha1(psw))+servertime+nonce);return password;}private String hex_sha1(String j) {return h(b(f(j,j.length()*g), j.length() * g));}private String h(int[] l){String k = i ?"0123456789ABCDEF" :"0123456789abcdef";String m = "";for (int j = 0; j <l.length * 4; j++) {m += k.charAt((l[j >> 2] >> ((3 - j % 4) * 8 + 4)) & 15) + "" + k.charAt((l[j >> 2] >> ((3 - j % 4) * 8)) & 15);}return m;}privateint[] b(int[] A,int r){A[r>>5]|=128<<(24-r%32);A[((r+64>>9)<<4)+15]=r;int[] B = newint[80];int z = 1732584193;int y = -271733879;int v = -1732584194;int u = 271733878;int s = -1009589776;for (int o = 0; o <A.length; o += 16) {int q = z;int p = y;int n = v;int m = u;int k = s;for (int l = 0; l < 80; l++) {if (l < 16) {B[l] = A[o + l];} else {B[l] = d(B[l - 3] ^ B[l - 8] ^ B[l - 14] ^ B[l - 16], 1);}int C = e(e(d(z, 5), a(l, y, v, u)), e(e(s, B[l]), c(l)));s = u;u = v;v = d(y, 30);y = z;z = C;}z = e(z, q);y = e(y, p);v = e(v, n);u = e(u, m);s = e(s, k);}returnnewint[]{z,y,v,u,s};}privateint a(int k,int j,int m,int l){if(k<20){return(j&m)|((~j)&l);};if(k<40){return j^m^l;};if(k<60){return(j&m)|(j&l)|(m&l);};return j^m^l;}privateint c(int j){return(j<20)?1518500249:(j<40)?1859775393:(j<60)?-1894007588:-8994975 14;}privateint e(int j, int m) {int l = (j & 65535) + (m & 65535);int k = (j >> 16) + (m >> 16) + (l >> 16);return (k << 16) | (l & 65535);}privateint d(int j,int k){return(j<<k)|(j>>>(32-k));}privateint[] f(String m,int r){int[] l;int j = (1<<this.g)-1;int len=((r+64>>9)<<4)+15;int k;for(k=0;k<m.length()*g;k+=g){len = k>>5>len?k>>5:len;}l = newint[len+1];for(k=0;k<l.length;k++){l[k]=0;}for(k=0;k<m.length()*g;k+=g){l[k>>5]|=(m.charAt(k/g)&j)<<(24-k%32);}return l;}}。

php 模拟GMAIL,HOTMAIL(MSN),YAHOO,163,126邮箱登录

php 模拟GMAIL,HOTMAIL(MSN),YAHOO,163,126邮箱登录
foreach($name as $v) {
preg_match('/<input\s*type="hidden"\s*name="'.$v.'"\s*id="'.$v.'"\s*value="(.*?)"\s*\/>/i', $contents, $matches);
1.GMAIL
PHP code
<?php
define( "COOKIEJAR", tempnam( ini_get( "upload_tmp_dir" ), "cookie" ) ); //定义COOKIES存放的路径,要有操作的权限
define( "TIMEOUT", 1000 ); //超时设定
$str = "<?xml version=\"1.0\"?><object><array name=\"items\"><object><string name=\"func\">pab:searchContacts</string><object name=\"var\"><array name=\"order\"><object><string name=\"field\">FN</string><boolean name=\"ignoreCase\">true</boolean></object></array></object></object><object><string name=\"func\">user:getSignatures</string></object><object><string name=\"func\">pab:getAllGroups</string></object></array></object>";

用HttpWebRequest 模拟网站登录

用HttpWebRequest 模拟网站登录
myHttpWebRequest.CookieContainer = myCookieContainer;//*解析到的CookieContainer
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myHttpWebRequest.CookieContainer = myCookieContainer;//*
//刚才那个CookieContainer已经存有了Cookie,把它附加到HttpWebRequest中则能直接通过验证
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
用HttpWebRequest 模拟网站登录
C# 2009-07-03 14:40 阅读88 评论0 字号: 大大 中中 小小 用HttpWebRequest 模拟网站登录时,如何将存在本机电脑中cookies文件中的cookies解析出来并一同提交?
例如本机电脑中cookies文件中存有一网站登录的用户名和密码,如何将用户名和密码从cookies解析出来并一同提交:
myHttpWebResponse.Cookies = myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);
myResponseStream = myHttpWebResponse.GetResponseStream();
static void Post(string url, string indata)
{
string outdata = "";

安卓模拟账户登录操作说明(1)

安卓模拟账户登录操作说明(1)

1、打开主页并给我一个截图,选中左上角红色图标Open the home page and give me a screenshot2、点击“管理账户”,选择“+”Click on “Manage Account” and select “+”3.选择“登录一个已有账户”,搜索“GlobalOnlineMarket-Asia”并添加它Select "Sign in to an existing account";Search for "GlobalOnlineMarket-Asia" and add it3、输入帐号和密码,并选择“Sign in”Enter your account number and password and select "Sign in"4、返回主页,给我截图return to the home page, give me a screenshot5、选择“+”,然后选择“Crypto-m”,最后选择“BTCUSD”Select “+”, then “Crypto-m”, and finally “BTCUSD”6、完成所有步骤,返回主页Complete all steps and return to the home page7、点击BTCUSD,选择打开图表Click BTCUSD and select Open Chart8、返回主页,点击BTCUSD,选择新交易Go back to the home page, click BTCUSD, select new transaction9、选择交易的数量和交易的方向。

Choose the transaction quantity and the direction of the transaction.10、点击上方我标记的地方,为交易数量,你可以在这设置数量,现在你尝试把交易数量改为0.1。

模拟登陆注册

模拟登陆注册

1.建一个User类,类中结构有用户名、密码、注册日期三个属性,一个注册方法和一个登录方法。

2.建一个Data类,用一个List装载用户数据,有保存数据,读取数据的方法。

3.利用对象流,读写List,实现登陆,注册功能。

我的主要思路是,User类里注册方法,需要有一个保存到List并写入磁盘的方法,我写在F盘。

于是调用了Data类的保存方法,传一个生成的User对象过去即可。

然后保存方法,就是先读取,但是要判断文件是否存在,如果不存在,就保存数据在new 出来的List里,如果存在,就读取磁盘的数据,赋予到new出来的list里。

import java.io.Serializable;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Scanner;/*** 建一个User类,类中结构有用户名、密码、注册日期三个属性,一个注册方法和一个登录方法*/public class Users implements Serializable {/*** Scanner不能放外面,会被序列化的*/private String name;private String pasw;private String apldate;public Users() {super();}public Users(String name, String pasw, String apldate) { = name;this.pasw = pasw;this.apldate = apldate;}public String getName() {return name;}public void setName(String name) { = name;public String getPasw() {return pasw;}public void setPasw(String pasw) {this.pasw = pasw;}public String getApldate() {return apldate;}public void setApldate(String apldate) {this.apldate = apldate;}public Users regist() throws Exception {@SuppressWarnings("resource")Scanner input = new Scanner(System.in);Data data = new Data();String name, pasw, apldate;System.out.println("客官,请输入一个用户名(*^__^*) ↗"); name = input.next();System.out.println("额……还有你的密码呢?(⊙o⊙)");pasw = input.next();SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");apldate = simpleDateFormat.format(new Date());Users u = new Users(name, pasw, apldate);// 生成一个用户对象data.saveList(u);System.out.println("注册成功!请吃饭!");return u;}public void signin() throws Exception {@SuppressWarnings("resource")Scanner input = new Scanner(System.in);ArrayList<Users> list = new ArrayList<Users>();Data data = new Data();// 准备加载数据………………list = data.readList();// 返回一个list,有很多用户的String name, paswInput;System.out.println("客官,请输入你的用户名^皿~");name = input.next();System.out.println("客官你的密码呢?O(∩_∩)O哈哈~"); paswInput = input.next();// 用户输入的密码int flag = 0;// 1.登陆成功2.密码不对3.未注册for (Users users : list) {if (users.getName().equals(name)) {// 已成功注册的用户if (users.getPasw().equals(paswInput)) {// 登陆成功flag = 1;break;// 一定要break出来,不然最后还是会变成3} elseflag = 2;break;// 一定要break出来,不然最后还是会变成3} elseflag = 3;// break;// 不能有break,不然跳出来后面的遍历不出了}switch (flag) {case 1:System.out.println("登陆成功!客官请慢用!");break;case 2:System.out.println("密码不对哦~~~~(>_<)~~~~");break;case 3:System.out.println("客官貌似你还没注册呢~~~");break;}}}②Data类[java] view plaincopyimport java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.ArrayList;public class Data {String path = "F:\\list.dat";ArrayList<Users> list = new ArrayList<Users>();public void saveList(Users u) throws Exception {//如果文件不存在,而去读,会出错,要判断一下,如果没有文件,就写一个,不要读File file = new File(path);if(file.exists()==true){list = readList();//有就读出来用,没有就用new出来的}list.add(u);FileOutputStream fos = new FileOutputStream(path);ObjectOutputStream oos = new ObjectOutputStream(fos);// 包装一个输出对象流oos.writeObject(list);// 覆盖保存到原来路径oos.flush();oos.close();}@SuppressWarnings("unchecked")public ArrayList<Users> readList() throws IOException,ClassNotFoundException {FileInputStream fis = new FileInputStream(path);ObjectInputStream ois = new ObjectInputStream(fis);ArrayList<Users> list = (ArrayList<Users>) ois.readObject();// 读入Listois.close();// 关闭对象流return list;}}③注册,登陆[java] view plaincopyimport java.util.Scanner;public class LogInLogOut {@SuppressWarnings("resource")public static void main(String[] args) throws Exception {Users users = new Users();// 初始化用户对象Scanner input = new Scanner(System.in);String temp = null;System.out.println("这位客官,欢迎光临!登陆请按“D”,注册请按“Z”,~(^o^)~,离开请按任意键");temp = input.next().toUpperCase();// 接收到转化为大写的if (temp.equals("D")) {// 调用用户对象的登陆方法users.signin();} else if (temp.equals("Z")) {// 注册users.regist();} elseSystem.out.println("呵呵,拜拜~(你妹啊……酱油党)");}。

Python爬虫模拟登陆哔哩哔哩(bilibili)并突破点选验证码功能

Python爬虫模拟登陆哔哩哔哩(bilibili)并突破点选验证码功能

Python爬⾍模拟登陆哔哩哔哩(bilibili)并突破点选验证码功能⽬录写在前⾯⼀、需求分析⼆、编程思路三、前期准备1.下载chrome driver2.安装selenium库3.对接打码平台三、完整代码写在前⾯ 今天带给⼤家⼀个突破点选验证码的案例,利⽤爬⾍模拟登陆哔哩哔哩,并且把⼀些采坑的地⽅给⼤家强调⼀下,避免⼤家想我⼀样(唉,菜鸡本菜)还是⽼规矩在⽂末会附上完整代码,需要的⼩伙伴⾃取就好了,能帮助到你的话别忘了点赞关注喔~ 郑重声明:本⼈⽬前仅在CSDN这⼀个平台发布⽂章,其他⼩伙伴如果想转载或者引⽤请注明引⽤来源,未经许可不得直接搬运,请尊重创作⼈的劳动成果,谢谢!⼀、需求分析 模拟登陆哔哩哔哩效果图如下:验证成功后会⾃动跳转B站的登录界⾯,为了保护我的信息安全,我⽤了假⽤户名,当然如果各位⼩伙伴⾮常想加我的话,欢迎私聊加VX喔((✿◡‿◡))⼆、编程思路 ⾸先利⽤xpath或者css选择器等⽅法找到要输⼊内容的元素位置,然后⽤⾃动化爬⾍⼯具Selenium模拟点击输⼊等操作来进⾏登录并分析页⾯,获取点选验证码的点选图⽚,通过将图⽚发送给快识别打码平台识别后获取坐标信息,根据快识别返回的数据,模拟坐标的点选,即可实现登录。

三、前期准备1.下载chrome driver 就是下载⾕歌浏览器的驱动器,当然如果你⽤其他浏览器那么就要下载其他浏览器的相应驱动,这⾥我以chrome浏览器为例,为什么要⽤英⽂呢?啊,这还⽤问当然是为了洋⽓啦!(⼿动狗头) 下载驱动的时候必须要下载相应的版本,可以在浏览器上⽅输⼊chrome://version,即可查看⾃⼰的chrome版本。

2.安装selenium库 由于是第三⽅库,所以在使⽤selenium之前需要先安装:pip install selenium3.对接打码平台代码如下:#快识别⽹址 /#interfaceimport base64import jsonimport requestsdef base64_api(uname,pwd,img):'''验证码识别接⼝:param uname: 快识别⽤户名:param pwd: 快识别密码:param img: 图⽚路径:return: 返回识别结果'''with open(img, 'rb') as f:base64_data = base64.b64encode(f.read())b64 = base64_data.decode()data = {"username": uname, "password": pwd, "image": b64,"typeid":21}#result = json.loads(requests.post("/base64", json=data).text)result = json.loads(requests.post("/imageXYPlus", json=data).text)if result['success']:return result["data"]["result"]else:return result["message"]三、完整代码 代码中的⼀些难点和相关步骤我都做了注释,根据上⾯给出的编程思路⼤家⼀步⼀步做就好了,我就不再详细解释了,如果任何问题欢迎评论区提问或者私信我都可以喔~ #login_bilibilifrom selenium import webdriverimport timefrom PIL import Imagefrom selenium.webdriver import ActionChains #导⼊动作链模块KUAI_USERNAME = '快识别账号'KUAI_PASSWORD = '快识别密码'USERNAME = 'B站账号'PASSWORD = 'B站密码'#创建浏览器对象driver = webdriver.Chrome(executable_path='chromedriver.exe')#打开请求⽹页页⾯driver.get('https:///login')driver.implicitly_wait(10) #隐式等待浏览器渲染完成,sleep是强制等待#driver.execute_script("document.body.style.zoom='0.67'") #浏览器内容缩放67%driver.maximize_window()#最⼤化浏览器'''⽤selenium⾃动化⼯具操作浏览器,操作的顺序和平常⽤浏览器操作的顺序是⼀样的''''''找到⽤户名和密码框输⼊密码'''user_input = driver.find_element_by_xpath('//*[@id="login-username"]') #使⽤xpath定位⽤户名标签元素user_input.send_keys(USERNAME)time.sleep(1)user_input = driver.find_element_by_xpath('//*[@id="login-passwd"]') #⽤户密码标签user_input.send_keys(PASSWORD)time.sleep(1)#点击登录Login_input = driver.find_element_by_css_selector('#geetest-wrap > div > div.btn-box > a.btn.btn-login')Login_input.click()time.sleep(5)#对图⽚验证码进⾏提取img_label = driver.find_element_by_css_selector('body > div.geetest_panel.geetest_wind > div.geetest_panel_box.geetest_no_logo.geetest_panelshowclick > div.geetest_panel_next > div > div') #提取图⽚标签#保存图⽚driver.save_screenshot('big.png') #截取当前整个页⾯time.sleep(5)#location可以获取这个元素左上⾓坐标print(img_label.location)#size可以获取这个元素的宽(width)和⾼(height)print(img_label.size)#计算验证码的左右上下横切⾯left = img_label.location['x']top = img_label.location['y']right = img_label.location['x'] + img_label.size['width']down = img_label.location['y'] + img_label.size['height']im = Image.open('big.png')im = im.crop((left,top,right,down))im.save('yzm.png')#对接打码平台from interface import base64_api #显⽰报错也⽆妨,可以运⾏的不要被唬住img_path = 'yzm.png'result = base64_api(uname=KUAI_USERNAME, pwd=KUAI_PASSWORD, img=img_path)print(result)print('验证码识别结果:', result)result_list = result.split('|')for result in result_list:x = result.split(',')[0]y = result.split(',')[1]ActionChains(driver).move_to_element_with_offset(img_label, int(x), int(y)).click().perform() # perform()执⾏整个动作链#点击确认按钮driver.find_element_by_css_selector('body > div.geetest_panel.geetest_wind > div.geetest_panel_box.geetest_no_logo.geetest_panelshowclick > div.geetest_panel_next > div > div > div.geetest_panel > a > div').click()input() # ⽤户输⼊阻塞浏览器关闭# 关闭浏览器driver.quit()注:chrome driver⼀定要和项⽬⽂件放在⼀起,这样更加⽅便也更稳定。

java如何登陆163邮箱,获取登陆用户的好友列表(模拟登录)

java如何登陆163邮箱,获取登陆用户的好友列表(模拟登录)
}
return true;
}
/**
*发送附件
*
* @param copyto
* @return
*/
public boolean setCopyTo(String copyto) {
System.out.println("发送附件到");
if (copyto == null)
return false;
if (to == null)
return false;
try {
mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO,
InternetAddress.parse(to));
} catch (Exception e) {
return false;
* @return
*/
public boolean addFileAffix(String filename) {
System.out.println("增加邮件附件:" + filename);
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
//发送的附件前加上一个用户名的前缀
bp.setFileName(fileds.getName());
//添加附件
mp.addBodyPart(bp);
} catch (Exception e) {

C#(WINFORM)实现模拟POST发送请求登录网站

C#(WINFORM)实现模拟POST发送请求登录网站
newStream.Close();
}
else
{
req.ContentLength = 0;
}
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = { '?', '=', '&' };
byte[] SomeBytes = null;
//输出
this.webBrowser1.Document.Write(strResult);
C#(WINFORM)实现模拟POST发送请求登录网站
作者:不详 来源:整理 发布时间:2007-8-5 14:29:24 发布人:Polaris
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
res.Close();
}
}
return strResult;
}
/**//// <summary> 获取页面HTML
/// </summary>
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Headers["If-None-Match"] = "36d0ed736e88c71:d9f";
req.Referer = "http://website/login.do";

c# 实现网页上用户自动登陆.net 模拟网站登录

c# 实现网页上用户自动登陆.net 模拟网站登录

using System;using System.Collections.Generic;using System.Text;using ;using System.IO;namespace Czt.Web{/// <summary>/// 实现网站登录类/// </summary>public class Post{/// <summary>/// 网站Cookies/// </summary>private string _cookieHeader = string.Empty;public string CookieHeader{get{return _cookieHeader;}set{_cookieHeader = value;}}/// <summary>/// 网站编码/// </summary>private string _code = string.Empty;public string Code{get { return _code; }set { _code = value; }}private string _pageContent = string.Empty;public string PageContent{get { return _pageContent; }set { _pageContent = value; }}private Dictionary<string, string> _para = new Dictionary<string, string>();public Dictionary<string, string> Para{get { return _para; }set { _para = value; }}/**//// <summary>/// 功能描述:模拟登录页面,提交登录数据进行登录,并记录Header中的cookie/// </summary>/// <param name="strURL">登录数据提交的页面地址</param>/// <param name="strArgs">用户登录数据</param>/// <param name="strReferer">引用地址</param>/// <param name="code">网站编码</param>/// <returns>可以返回页面内容或不返回</returns>public string PostData(string strURL, string strArgs, string strReferer, string code, string method){return PostData(strURL, strArgs, strReferer, code, method, string.Empty);}public string PostData(string strURL, string strArgs, string strReferer, string code, string method, string contentType){try{string strResult = "";HttpWebRequest myHttpWebRequest =(HttpWebRequest)WebRequest.Create(strURL);myHttpWebRequest.AllowAutoRedirect = true;myHttpWebRequest.KeepAlive = true;myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg,image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";myHttpWebRequest.Referer = strReferer;erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";if (string.IsNullOrEmpty(contentType)){myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";}else{myHttpWebRequest.ContentType = "contentType";}myHttpWebRequest.Method = method;myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");if (myHttpWebRequest.CookieContainer == null){myHttpWebRequest.CookieContainer = new CookieContainer();}if (this.CookieHeader.Length > 0){myHttpWebRequest.Headers.Add("cookie:" + this.CookieHeader);myHttpWebRequest.CookieContainer.SetCookies(new Uri(strURL), this.CookieHeader);}byte[] postData = Encoding.GetEncoding(code).GetBytes(strArgs);myHttpWebRequest.ContentLength = postData.Length;System.IO.Stream PostStream = myHttpWebRequest.GetRequestStream();PostStream.Write(postData, 0, postData.Length);PostStream.Close();HttpWebResponse response = null;System.IO.StreamReader sr = null;response = (HttpWebResponse)myHttpWebRequest.GetResponse();if (myHttpWebRequest.CookieContainer != null){this.CookieHeader =myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(strURL));}sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding(code)); // //utf-8strResult = sr.ReadToEnd();sr.Close();response.Close();return strResult;}catch (Exception ex){Utilities.Document.Create("C:\\error.log", strArgs, true, Encoding.UTF8);}return string.Empty;}/**//// <summary>/// 功能描述:在PostLogin成功登录后记录下Headers中的cookie,然后获取此网站上其他页面的内容/// </summary>/// <param name="strURL">获取网站的某页面的地址</param>/// <param name="strReferer">引用的地址</param>/// <returns>返回页面内容</returns>public string GetPage(string strURL, string strReferer, string code){return GetPage(strURL, strReferer,code,string.Empty);}public string GetPage(string strURL, string strReferer,string code,string contentType) {string strResult = "";HttpWebRequest myHttpWebRequest =(HttpWebRequest)WebRequest.Create(strURL);myHttpWebRequest.AllowAutoRedirect = true;myHttpWebRequest.KeepAlive = false;myHttpWebRequest.Accept = "*/*";myHttpWebRequest.Referer = strReferer;myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";if (string.IsNullOrEmpty(contentType)){myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";}else{myHttpWebRequest.ContentType = contentType;}myHttpWebRequest.Method = "GET";if (myHttpWebRequest.CookieContainer == null){myHttpWebRequest.CookieContainer = new CookieContainer();}if (this.CookieHeader.Length > 0){myHttpWebRequest.Headers.Add("cookie:" + this.CookieHeader);myHttpWebRequest.CookieContainer.SetCookies(new Uri(strURL),this.CookieHeader);}HttpWebResponse response = null;System.IO.StreamReader sr = null;response = (HttpWebResponse)myHttpWebRequest.GetResponse();Stream streamReceive;string gzip = response.ContentEncoding;if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip"){streamReceive = response.GetResponseStream();}else{streamReceive = newpression.GZipStream(response.GetResponseStream(),pressionMode.Decompress);}sr = new System.IO.StreamReader(streamReceive, Encoding.GetEncoding(code));if (response.ContentLength > 1){strResult = sr.ReadToEnd();}else{char[] buffer=new char[256];int count = 0;StringBuilder sb = new StringBuilder();while ((count = sr.Read(buffer, 0, buffer.Length)) > 0){sb.Append(new string(buffer));}strResult = sb.ToString();}sr.Close();response.Close();return strResult;}}}。

模拟telnet登录的程序

模拟telnet登录的程序

模拟telnet登录的程序,包括服务器和测试客户端,主要思想其实是很简单,就是:服务器保存了一些users和相关的password,客户端想登录就输入用户名,然后客户端把用户名发送到服务器上,服务器检查是否存在该用户,存在就提示用户输入密码,不存在,就输出错误信息,接下来就是同样道理,检查密码了。

代码很短,因为本来就简单,接下来可能会完善这个程序,让它模拟telnet服务器的操作,而不是单单登录而已。

#---------------------------------------------------------------------#ifndef TELNET_H#define TELNET_H#define PORT 8003#define MAX_LISTEN 10#define BUF_SIZE 1024#define MAX_LEN 125#define TRUE 1#define FALSE -1#define USERNAME 0#define PASSWORD 1struct user_info {char username[ MAX_LEN ];char password[ MAX_LEN ];};struct user_info users[] = {{ "ken", "ken" },{ "linux", "123" },{ "admin", "123" },{ " ", " " },};char *error_user = "error user name";char *error_password = "error password";char *correct_user = "correct user";char *success_login = "login, welcome";#endif#---------------------------------------------------------------------#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#include <netinet/in.h>#include "telnet.h"/** @connfd: the file desc of the connection* @string: the message string* DESC: input the login name and password*/int input_client_info( int connfd, const char *string, char flag ) {char input_buf[ BUF_SIZE ];char recv_buf[ BUF_SIZE ];printf( "%s: ", string );fgets( input_buf, BUF_SIZE, stdin );input_buf[strlen(input_buf) - 1] = '\0';/* send the result to the sever point */if ( send(connfd, input_buf, BUF_SIZE, 0) < 0 )printf( "send failed" );/* recv the message from the sever */if ( recv(connfd, recv_buf, BUF_SIZE, 0) < 0 )printf( "recv failed" );if ( flag == 'u' ) {/* whether the user name is error */if ( strcmp(recv_buf, error_user) == 0 ) {puts( error_user );return FALSE;}}else if ( flag == 'p' ) {/* whether the password is error */if ( strcmp(recv_buf, error_password) == 0 )puts( error_password );elseputs( success_login );}return TRUE;}int main( int argc, char *argv[] ){int connfd;int serv_port;char recv_buf[ BUF_SIZE ];struct sockaddr_in serv_addr;if ( argc != 3 ) {printf( "usage: ./telnet_client [port] [ip]\n" );exit ( 1 );}memset( &serv_addr, 0, sizeof(struct sockaddr_in) );serv_addr.sin_family = AF_INET;serv_addr.sin_port = htons( atoi(argv[1]) );inet_aton( argv[2], &serv_addr.sin_addr );if ( serv_addr.sin_port == 0 ||serv_addr.sin_addr.s_addr == 0 ) { fprintf( stderr, "usage: ./telnet_client [port] [ip]\n" );exit ( 1 );}connfd = socket( AF_INET, SOCK_STREAM, 0 );if ( connfd < 0 )printf( "socket failed" );if ( connect(connfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) < 0 )printf( "connect failed" );if ( input_client_info( connfd, "username", 'u' ) == TRUE ) input_client_info( connfd, "password", 'p' );close( connfd );return 0;}#-------------------------------------------------------------------- #include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#include <netinet/in.h>#include "telnet.h"/** @name: the user name from client point* DESC: to find the name in the server point*/int find_user_name( const char *name ){assert( name != NULL );for ( int i = 0; users[i].username[0] != ' '; ++i )if ( strcmp(users[i].username, name) == 0 )return i;return FALSE;}int main( int argc, char *argv[] ){int sockfd, connfd;int optval;int recv_type = USERNAME;int client_size;int recv_bits;int name_index;char buffer[ BUF_SIZE ];pid_t pid;struct sockaddr_in client_addr, server_addr;/* initialize some variables */client_size = sizeof( struct sockaddr_in );memset( buffer, 0, BUF_SIZE );memset( &server_addr, 0, sizeof(server_addr) );memset( &client_addr, 0, sizeof(server_addr) );if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )printf( "socket failed" );/* set the option and the sockfd can rebind points */optval = 1;if ( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,(void *)&optval, sizeof(int)) < 0 )printf( "setsockopt failed" );server_addr.sin_family = AF_INET;server_addr.sin_port = htons( PORT );server_addr.sin_addr.s_addr = htonl( INADDR_ANY );if ( bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0 ) printf( "bind failed" );if ( listen(sockfd, MAX_LISTEN) < 0 )printf( "listen failed" );while ( 1 ) {if ( (connfd = accept(sockfd, (struct sockaddr*)&client_addr, &client_size)) < 0 ) printf( "accept failed" );printf( "Server accept a client: ip = %s\n",inet_ntoa(client_addr.sin_addr) );/* the child process is used to deal with the connection */if ( (pid = fork()) == 0 ) {while ( 1 ) {/* recieve the string from the client point */if ( (recv_bits = recv(connfd, buffer, BUF_SIZE, 0)) < 0 )printf( "recv failed" );/* delete the last character of the buffer string */buffer[recv_bits - 1] = '\0';puts(buffer);/* the buffer is user's name */if ( recv_type == USERNAME ) {name_index = find_user_name( buffer );if ( name_index == FALSE ) {if ( send(connfd, error_user, strlen(error_user), 0) < 0 )printf( "send failed" );break;} else {if (send(connfd, correct_user, strlen(correct_user), 0) < 0 )printf( "send failed" );recv_type = PASSWORD;}}/* the buffer is user's password */else if ( recv_type == PASSWORD ) {if ( strcmp(users[name_index].password, buffer) != 0 ) {if ( send(connfd, error_password,strlen(error_password), 0) < 0 )printf( "send failed" );} else {if ( send(connfd, success_login, strlen(success_login), 0) < 0 )printf( "send failed" );}break;}}close( sockfd );close( connfd );exit ( 0 );}elseclose( connfd );}return 0;}。

AVL树模拟用户登录系统的实验报告(附代码和详尽注释) (2)

AVL树模拟用户登录系统的实验报告(附代码和详尽注释) (2)

一.实验内容分析:1.实验目的:模拟用户登录系统,在O(lgn)时间内完成用户登录、删除、修改等工作。

2.设计思路:主要分以下四个类:A VLTreeNode:存储平衡树节点;A VLTree:A VL平衡树的主要实现算法;UserInfo:存储用户信息;Interface:界面,与用户交互;3.流程图以及类的主要包含和调用关系:二.实验验证分析(1)输入的形式和输入值的范围;控制台的输入:如图,输入为数字,超出范围将提示不正确并返回重新输入文件的输入:程序会找寻当前目录的database.data文件,并读入数据,如果未找到则自创此文件,创建空树(2)输出的形式;程序退出时析构函数保存文件到database.data并覆盖原文件。

(3)程序所能达到的功能;在O(lgn)时间内添加、查找、删除、修改用户信息。

(4)测试数据:本系统包含三个测试函数样例:1.顺序插入测试(分别在debug和release环境下和STL map比较速度)2.随机插入测试(分别在debug和release环境下和STL map比较速度)3.删除测试测试函数均在main文件里void randomTest();//随机数测试void orderTest();//顺序插入测试void deleteTest();//删除测试void main_interface();//主界面1,2均在debug模式下插入100W数据,在release模式下插入1000W数据。

顺序插入的实现是用整数1~n转换为string,位数不够的在前面补‘0’。

测试结果:1.debug下顺序插入测试:2.Release下顺序插入测试3.debug下随机插入测试4.release下随机插入测试实践证明map的红黑树在顺序插入测试时慢于我的avl树,但随机插入测试表现比A VL树要好。

3.删除数据的图形化表示(‘R’‘L’‘=’为平衡因子以检验正确性)下面删除3(树中无3):还是一样,下面删除2删除成功,下面删除7删除成功。

安全生产模拟考试云平台登录

安全生产模拟考试云平台登录

安全生产模拟考试云平台登录安全生产是企业发展的基石,也是国家的重要政策。

为了加强对安全生产的管理和监督,提高从业人员的安全意识和技能水平,我国建立了安全生产模拟考试云平台。

通过该平台,从业人员可以进行安全生产知识的学习和考核,以确保他们具备必要的安全生产知识和技能。

要登录安全生产模拟考试云平台,首先需要拥有一个有效的账号。

只有通过合法渠道注册并获得账号的用户才能登录平台进行学习和考核。

在注册账号时,用户需要提供真实的个人信息,以确保平台能够准确记录用户的学习和考核情况,并为用户提供个性化的学习服务。

一旦拥有了有效的账号,用户就可以通过输入账号和密码的方式登录安全生产模拟考试云平台。

在输入账号和密码后,系统会对用户的身份进行验证,确保只有合法用户才能进入平台。

这样可以有效防止非法用户的进入,保障平台的安全性和稳定性。

登录后,用户可以根据自己的需求选择不同的学习和考核内容。

平台提供了丰富的安全生产知识库和模拟考题,用户可以根据自己的实际情况选择合适的学习内容进行学习和考核。

同时,平台还提供了学习记录和考核成绩的查询功能,用户可以随时查看自己的学习和考核情况,及时了解自己的学习进度和成绩情况。

除了学习和考核功能外,安全生产模拟考试云平台还提供了安全生产政策法规的查询和下载功能,用户可以通过平台了解最新的安全生产政策法规,及时了解国家对安全生产的最新要求,为自己的安全生产工作提供参考和指导。

总的来说,安全生产模拟考试云平台为从业人员提供了一个便捷、高效的学习和考核平台,帮助他们提高安全生产知识和技能水平,提高安全生产意识,确保安全生产工作的顺利进行。

希望广大从业人员能够充分利用这一平台,不断提升自己的安全生产水平,为企业的安全生产工作做出更大的贡献。

Vue+Mock.js模拟登录和表格的增删改查功能

Vue+Mock.js模拟登录和表格的增删改查功能

Vue+Mock.js模拟登录和表格的增删改查功能前⾔关于mockjs,官⽹描述的是1.前后端分离2.不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。

3.数据类型丰富4.通过随机数据,模拟各种场景。

5 项⽬不背锅(等后端给接⼝的话可能会背锅)等等优点,最后⼀条我加的。

第⼀步先安装mock.jsnpm install mockjs --save-dev第⼆步使⽤ mock.jsimport Mock from 'mockjs'哪⾥⽤就在哪⾥引⼊。

我是在项⽬src/mock/index.js⾥⾯使⽤mock.js关键点1:Mock.mock()Mock.mock( rurl?, rtype?, template|function( options ) )这⾥的参数都是可选:rurl(可选)。

表⽰需要拦截的 URL,可以是 URL 字符串或 URL 正则。

例如 //domain/list.json/、'/domian/list.json'。

rtype(可选)。

表⽰需要拦截的 Ajax 请求类型。

例如 GET、POST、PUT、DELETE 等。

template(可选)。

表⽰数据模板,可以是对象或字符串。

例如 { 'data|1-10':[{}] }、'@EMAIL'。

function(options)(可选)。

表⽰⽤于⽣成响应数据的函数。

options:指向本次请求的 Ajax 选项集。

关键点2:模板⽣成语法:数据模板中的每个属性由 3 部分构成:属性名、⽣成规则、属性值:// 属性名 name// ⽣成规则 rule// 属性值 value'name|rule': value属性名和⽣成规则之间⽤竖线 | 分隔。

⽣成规则是可选的。

⽣成规则有 7 种格式:'name|min-max': value'name|count': value'name|min-max.dmin-dmax': value'name|min-max.dcount': value'name|count.dmin-dmax': value'name|count.dcount': value'name|+step': value`⽣成规则的含义需要依赖属性值的类型才能确定。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

httpwebrequest 模拟登录获取cookies2个类,一个基类,一个构建头信息调用类关于如何获取到post中的内容,你之需要用http抓包工具把你与目标网站的请求信息抓下来后,打开分析下按照抓下来的包中的数据进行构建就行了using System;using System.Collections.Generic;using System.Text;using ;using System.IO;namespace bot{public class Html{////// httpwebrequest类中的一些属性的集合///public struct RequestPPT{private string strAccept;////// 获取或设置request类中的Accept属性/// 用以设置接受的文件类型///public string Accept{get{return strAccept;}set{strAccept = value;}}private string strContentType;////// 获取或设置request类中的ContentType属性/// 用以设置请求的媒体类型///public string ContentType{get{return strContentType;}set{strContentType = value;}}////// 获取或设置request类中的UserAgent属性/// 用以设置请求的客户端信息///private string strUserAgent;public string UserAgent{get{return strUserAgent;}set{strUserAgent = value;}}private string strMethod;////// 获取或设置request类中的Method属性/// 可以将Method 属性设置为任何HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或OPTIONS。

/// 如果ContentLength 属性被设置为-1 以外的任何值,则必须将Method 属性设置为上载数据的协议属性。

///public string Method{get{return strMethod;}set{strMethod = value;}}}////// 构建一个httt请求以获取目标链接的cookies,需要传入目标的登录地址和相关的post信息,返回完成登录的cookies,以及返回的html内容////// 登录页面的地址/// post信息/// 输出的html代码/// 请求的标头所需要的相关属性设置/// 请求完成后的cookiespublic CookieCollection funGetCookie(string url, byte[] post, out string strHtml, RequestPPT rppt,string server){CookieCollection ckclReturn = new CookieCollection();CookieContainer cc = new CookieContainer();HttpWebRequest hwRequest;HttpWebResponse hwResponse;//请求cookies的格式//hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));//hwResponse = (HttpWebResponse)hwRequest.GetResponse();//string cookie = hwResponse.Headers.Get("Set-Cookie");//cookie = cookie.Split(';')[0];//hwRequest = null;//hwResponse = null;//构建即将发送的包头//cc.SetCookies(new Uri(server), cookie);hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));hwRequest.CookieContainer = cc;hwRequest.Accept = rppt.Accept;hwRequest.ContentType = rppt.ContentType;erAgent = erAgent;hwRequest.Method = rppt.Method;hwRequest.ContentLength = post.Length;//写入标头Stream stream;stream = hwRequest.GetRequestStream();stream.Write(post, 0, post.Length);stream.Close();//发送请求获取响应内容try{hwResponse = (HttpWebResponse)hwRequest.GetResponse();}catch{strHtml = "";return ckclReturn;}stream = hwResponse.GetResponseStream();StreamReader sReader = new StreamReader(stream, Encoding.Default);strHtml = sReader.ReadToEnd();sReader.Close();stream.Close();//获取缓存内容ckclReturn = hwResponse.Cookies;return ckclReturn;}////// 根据已经获取的有效cookies来获取目标链接的内容////// 目标链接的url/// 已经获取到的有效cookies/// 头属性的相关设置/// 目标连接的纯文本:"txt/html"public string funGetHtmlByCookies(string strUri, CookieCollection ccl, RequestPPT rppt) {CookieContainer cc = new CookieContainer();HttpWebRequest hwRequest;HttpWebResponse hwResponse;//构建即将发送的包头hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(strUri));cc.Add(ccl);hwRequest.CookieContainer = cc;hwRequest.Accept = rppt.Accept;hwRequest.ContentType = rppt.ContentType;erAgent = erAgent;hwRequest.Method = rppt.Method;hwRequest.ContentLength = 0;//发送请求获取响应内容try{hwResponse = (HttpWebResponse)hwRequest.GetResponse();}catch{return "";}Stream stream;stream = hwResponse.GetResponseStream();StreamReader sReader = new StreamReader(stream, Encoding.Default);string strHtml = sReader.ReadToEnd();sReader.Close();stream.Close();//返回值return strHtml;}////// 根据已经获取的有效cookies来获取目标链接的内容////// 目标链接的url///post的byte信息/// 已经获取到的有效cookies/// 头属性的相关设置/// 目标连接的纯文本:"txt/html"public string funGetHtmlByCookies(string strUri,byte[] post, CookieCollection ccl, RequestPPT rppt){CookieContainer cc = new CookieContainer();HttpWebRequest hwRequest;HttpWebResponse hwResponse;//构建即将发送的包头hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(strUri));cc.Add(ccl);hwRequest.CookieContainer = cc;hwRequest.Accept = rppt.Accept;hwRequest.ContentType = rppt.ContentType;erAgent = erAgent;hwRequest.Method = rppt.Method;hwRequest.ContentLength = post.Length;//写入post信息Stream stream;stream = hwRequest.GetRequestStream();stream.Write(post, 0, post.Length);stream.Close();//发送请求获取响应内容try{hwResponse = (HttpWebResponse)hwRequest.GetResponse();}catch{return"" ;}stream = hwResponse.GetResponseStream();StreamReader sReader = new StreamReader(stream, Encoding.Default);string strHtml = sReader.ReadToEnd();sReader.Close();stream.Close();//返回值return strHtml;}}} 第二个using System;using System.IO;using System.Collections.Generic;using System.Text;using ;using System.Data;using System.Xml;using System.Text.RegularExpressions;namespace bot{public class SisHtml :Html{public SisHtml(){}/// <summary>/// 设置主机ip地址/// </summary>public string Host{get {return strHost;}set {strHost = value;}}private string strHost;/// <summary>/// 获取目标登录链接的cookies/// </summary>/// <param name="url">目标的登录链接</param>/// <param name="dir">构造头的泛型键值对</param>/// <param name="strHtml">登录后返回的页面内容</param>/// <returns>登录后的cookies</returns>public CookieCollection funGetCookie(string url, Dictionary<string, string> dir, out string strHtml){CookieCollection cc = new CookieCollection();RequestPPT rppt = new RequestPPT();//构建post内容string strPost = funMakePost(dir);byte[] post = Encoding.Default.GetBytes(strPost);//设置标头属性rppt.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";rppt.ContentType = "application/x-www-form-urlencoded";rppt.Method = "Post";erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";string server ="http://"+ new Uri(url).Host;return cc = base.funGetCookie(url, post, out strHtml, rppt, server);}/// <summary>/// 根据已经获取到cookies来获取目标链接的内容/// </summary>/// <param name="strUri">目标的url</param>/// <param name="ccl">已经获取好的cookies</param>/// <returns>目标url的纯文本:"txt/html"</returns>public string funGetHtmlByCookies(string strUri,CookieCollection ccl ){RequestPPT rppt = new RequestPPT();//设置头属性rppt.Accept = "txt/html";rppt.ContentType = "application/x-www-form-urlencoded";rppt.Method = "Post";erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";return base.funGetHtmlByCookies(strUri, ccl, rppt);}/// <summary>/// 投票帖子用的方法/// </summary>/// <param name="strHtml">投票帖子的htmlcode</param>/// <param name="ccl">有效的cookies</param>/// <returns>投票完成以后的htmlcode</returns>public string funVote(string strHtml,CookieCollection ccl){//判断是不是选取投票try{strHtml = strHtml.Substring(strHtml.IndexOf("<form"), stIndexOf("</form>") - strHtml.IndexOf("<form") + 7);}catch{return "";}string strCheck = @"name=""pollanswers[]""";//如果代码中包含关键信息说明没有被投票过if(strHtml.IndexOf(strCheck)>0){//获取post头的需求信息string strFormHash = "77b49df4";string strPollanswers;strPollanswers = strHtml.Substring(strHtml.IndexOf(strCheck)+strCheck.Length, 20).Split('"')[1];string strPollansubmit = "提交";Dictionary<string,string>dir = new Dictionary<string,string>();dir.Add("formhash",strFormHash);dir.Add("pollanswers[]",strPollanswers);dir.Add("pollsubmit",strPollansubmit);string strPost = funMakePost(dir);byte[] post = Encoding.Default.GetBytes(strPost);//获取请求的路径string strUrl= "http://"+Host+"/bbs/";string strActionUrl =@"method=""post""";strUrl+=strHtml.Substring(strHtml.IndexOf(strActionUrl)+strActionUrl.Length,100).Split('"')[1].Replace("a mp;","");//构建头RequestPPT rppt = new RequestPPT();rppt.Accept = "txt/html";rppt.ContentType = "application/x-www-form-urlencoded";rppt.Method = "Post";erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";strHtml = base.funGetHtmlByCookies(strUrl, post, ccl, rppt);}return strHtml;}/// <summary>/// 根据泛型来构建字符串用于post/// </summary>/// <param name="dir">带有键值对的泛型</param>/// <returns>构建完毕的字符串</returns>private string funMakePost(Dictionary<string,string> dir){string strPost="";foreach (KeyValuePair<string, string> kvp in dir){strPost += kvp.Key + "=";if (kvp.Value == ""){strPost += "''";}else{strPost += kvp.Value;}strPost += "&";}strPost = strPost.Substring(0, strPost.Length - 1);return strPost;}/// <summary>/// 获取下一个列表页面的路径/// </summary>/// <param name="strHtml">当前页面的htmlcode</param>/// <returns>下一个列表页面的路径</returns>public string funGetNextUrl(string strHtml){string strUrl = "";//判断是否是列表型页面if (strHtml.IndexOf("<form") != -1){return strUrl;}string strKey =@"class=""next""";strUrl = "http://"+Host+"/bbs/"+strHtml.Substring(strHtml.IndexOf(strKey) - 100, 100).Split('"')[1].Replace("amp;", "");return strUrl;}public DataT able funGetListTable(string strHtml){DataTable dt = new DataT able();DataColumn dc = new DataColumn("Url");dt.Columns.Add(dc);DataRow dr ;string strReg = @"viewthread.php(\S)+highlight=";Regex rg = new Regex(strReg);MatchCollection mc = rg.Matches(strHtml);foreach (Match ms in mc){dr = dt.NewRow();dr[0] = "http://" + Host + "/bbs/" + ms.ToString().Replace("amp;", "");dt.Rows.Add(dr);}return dt;}}}本文来自CSDN博客,转载请标明出处:/atlasroben/archive/2008/07/29/2729958.aspx。

相关文档
最新文档