Форум сайта python.su
Готовлю ребенка к сдаче ГИА-9 (ОГЭ) по информатике. База вопросов выложена на сайте фипи. Сделано у них все весьма коряво: через сам сайт fipi зайти проблематично (там постоянно какие-то перебои). Получается зайти по ip: по такому адресу:
http://85.142.162.126/os/xmodules/qprint/index.php?theme_guid=4BE9873EF46DB209473CFCC27C95FA75&proj_guid=74676951F093A0754D74F2D6E7955F06
Задания тут представлены большим списком, без тем, без какой-либо группировки, не удобно очень.
Подумал написать небольшой скрипт для парсинга:
Во-первых, перед тем, как эту страницу открывать, нужно посетить:
http://85.142.162.126/os/xmodules/qprint/openlogin.php
На которой получить идентификатор сессии и с которой будет перенаправление.
Странички (как оказалось) в кодировке 1251, что для современного сайта, имхо, дичь.
Ну да ладно, это я поборол, но вот тут не могу разобраться и тут залип: после того, как делаю запрос к странице он возвращает мне ее без заданий. Хотя точно такой же запрос в браузере – дает результат. Дебаг по JS не помог, в ресурсах тоже ничего не нашел (думал может задания подгружаются в процессе). Возможно дело в MathJax? Может еще в чем.
Если кто-то сталкивался с чем-то подобным – помогите пожалуйста. Вот скрипт:
from bs4 import BeautifulSoup import lxml.html as html import requests s = requests.Session() headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} url = "http://85.142.162.126/os/xmodules/qprint/openlogin.php" r = requests.get(url, headers=headers) sid = r.cookies["PHPSESSID"] qreq = "http://85.142.162.126/os/project/questions/question_view.php?qst=%s&md=qprint" themes = [ ('ИиКТ','74676951F093A0754D74F2D6E7955F06', [ ('Информационные процессы','4BE9873EF46DB209473CFCC27C95FA75'), ('Информационные и коммуникационные технологии','0CB744F18A86A1C64D4EB577F422682B') ] ) ] def list_quest(sid, el): proj_guid = el[1] url = "http://85.142.162.126/os/xmodules/qprint/index.php?theme_guid=%s&proj_guid=%s&groupno=%d" for x in el[2]: theme_guid = x[1] print('Глава:', x[0]) groupno = 0 r = requests.get(url % (theme_guid, proj_guid, groupno), cookies={'PHPSESSID': sid}, headers=headers) r.encoding = 'cp1251' # walk soup = BeautifulSoup(r.text, 'html.parser') nums = soup.find_all('span', { "class" : "Walk" }) # if not len(nums): with open("c:\\temp\\1.html", "w", encoding='cp1251') as f: print(r.text, file=f) break return el print(list_quest(sid, themes[0]))
<html XMLNS:m="http://www.w3.org/1998/Math/MathML"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /><LINK href="../../docs/74676951F093A0754D74F2D6E7955F06.css" rel="STYLESHEET" type="text/css"> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script><script type="text/javascript" src="../../lib/t3utils.js"></script><meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> <META NAME="Document-state" CONTENT="Dynamic"><META HTTP-EQUIV="pragma" CONTENT="no-cache"><META HTTP-EQUIV="expires" CONTENT="0"><title>Открытый банк заданий ОГЭ</title> </head> <body class='coursebody' style='font-size:11pt'> <table width="100%" height="100%" cellspacing=0 cellpadding=0> <tr height='20px'><td colspan=2 > <script language="javascript"> var proj='74676951F093A0754D74F2D6E7955F06'; function QuestionEd() { location.href='index.php?proj='+proj; } function QuestionFav() { location.href='index.php?theme_guid=FAVOUR&proj='+proj; } function selectProject() { location.href='index.php'; } </script> <table border="0" width="100%" cellpadding="0" cellspacing="0"><tr> <td background="../../images/74676951F093A0754D74F2D6E7955F06/l3.gif"><img src="../../images/74676951F093A0754D74F2D6E7955F06/l2.gif"></td> <td background="../../images/74676951F093A0754D74F2D6E7955F06/l3.gif"><img src="../../images/74676951F093A0754D74F2D6E7955F06/l3.gif"></td> <td background="../../images/74676951F093A0754D74F2D6E7955F06/l3.gif"colspan="2" align=right> <img src="../../images/l8.gif"></td></tr> <tr><td colspan="2" background="../../images/74676951F093A0754D74F2D6E7955F06/gr_polosa.gif"> <table border="0" cellpadding="0" cellspacing="0" background="../../images/74676951F093A0754D74F2D6E7955F06/gr_polosa.gif"> <tr> <td height="33" width="0"> </td> <td width=10><img src='../../images/74676951F093A0754D74F2D6E7955F06/ptr.gif' align=top width=10 height=33 border=0></td><td width=35> <img border='0' src='../../images/i_2.gif' onmouseover='src="../../images/2.gif"' onmouseout='src="../../images/i_2.gif"' onclick="QuestionEd();" title='Разделы' align='absmiddle' style='cursor:pointer'><td width=35> <img border='0' src='../../images/i_3.gif' onmouseover='src="../../images/3.gif"' onmouseout='src="../../images/i_3.gif"' onclick="QuestionFav();" title='Отложенные задания' align='absmiddle' style='cursor:pointer'> <sup id='fav_cnt'>0</sup><td width=35> <img border='0' src='../../images/i_11.gif' onmouseover='src="../../images/11.gif"' onmouseout='src="../../images/i_11.gif"' onclick="QuestionStat();" title='Количество заданий по разделам' align='absmiddle' style='cursor:pointer'> </tr> </table> </td><td valign="center" align="right" background="../../images/74676951F093A0754D74F2D6E7955F06/gr_polosa.gif"> </td> </tr> <style> #chpr-a #chpr-img {border:0px; width:18px; height:18px; background: url(../../images/chcs.gif);} #chpr-a:hover #chpr-img {background: url(../../images/chcs_i.gif);} </style> <tr> <td colspan="4" background="../../images/74676951F093A0754D74F2D6E7955F06/l5.gif" valign="top"> <table border="0" cellpadding="0" cellspacing="0" height=28><tr><td><a id='chpr-a' href='javascript:selectProject()' title='Перейти к другому предмету'><span class="projname"> Открытый банк заданий ГИА-9 / Информатика и ИКТ</span></a></td><td background="../../images/74676951F093A0754D74F2D6E7955F06/l5.gif"> </td></tr></table> </td></tr></table> </td></tr> <tr valign=top> <td class='coursebody' width='10%'> <div style='width:300px; margin: 5px;'> <div style='margin-bottom:5px;' class=cell_2><a href='qsearch.php?theme_guid=4BE9873EF46DB209473CFCC27C95FA75&proj_guid=74676951F093A0754D74F2D6E7955F06'>Информационные процессы</a></div><div style='margin-bottom:5px;'><a href='qsearch.php?theme_guid=0CB744F18A86A1C64D4EB577F422682B&proj_guid=74676951F093A0754D74F2D6E7955F06'>Информационные и коммуникационные технологии</a></div> </div> </td> <td style='background-color:white' width='90%'> <table width=100% cellspacing=1px cellpadding=5px><tr><td> <style> #gl_container {font-size:80%; color: #A0A0A0} </style> <script language="JavaScript"> function printQThemes() { var wnd=open('question_print.php?proj_guid=74676951F093A0754D74F2D6E7955F06&theme_guid=4BE9873EF46DB209473CFCC27C95FA75', 'proppvwnd', 'scrollbars=1,resizable=1,width=600,height=400,left='+(screen.width-600)/2+',top='+(screen.height-400)/2 ); wnd.focus(); } var request; var requestInProgress = false; function generateFavLink() { if (requestInProgress) return; if (!request) request = createAJAXRequest(); requestInProgress = true; request.open('GET', 'gen_fav_link.php?proj_guid=74676951F093A0754D74F2D6E7955F06&tm=1477900079', true); request.onreadystatechange = showFavLink; request.send(null); document.getElementById('gl_container').innerHTML="<img src='../../images/aloader.gif' width='20' height='20'>"; } function showFavLink() { if (request.readyState==4) { requestInProgress = false; document.getElementById('gl_container').innerHTML = (request.status==200? request.responseText : 'Ошибка...'); } } var lastFVBtn; function add2fav(img, guid) { if (requestInProgress) return; if (!request) request = createAJAXRequest(); requestInProgress = true; lastFVBtn = img; lastFVBtn.src='../../images/aloader.gif'; request.open('GET', 'quest_preview.php?proj_guid=74676951F093A0754D74F2D6E7955F06&theme_guid=4BE9873EF46DB209473CFCC27C95FA75&tm=1477900079&ajax=1&add2fav='+guid, true); request.onreadystatechange = add2favDone; request.send(null); } function add2favDone() { if (request.readyState==4) { requestInProgress = false; if (lastFVBtn) lastFVBtn.parentNode.removeChild(lastFVBtn); lastFVBtn=null; setFavCnt(request.responseText); } } var lastSLVBtn; var lastSLVSet; function setSolved(img, guid, solved) { if (requestInProgress) return; if (!request) request = createAJAXRequest(); requestInProgress = true; lastSLVBtn = img; lastSLVBtn.guid = guid; lastSLVBtn.src='../../images/aloader.gif'; lastSLVSet = solved; request.open('GET', 'quest_preview.php?proj_guid=74676951F093A0754D74F2D6E7955F06&theme_guid=4BE9873EF46DB209473CFCC27C95FA75&tm=1477900079&ajax=1&'+(solved?'':'re')+'set_solved='+guid, true); request.onreadystatechange = setSolvedDone; request.send(null); } function setSolvedDone() { if (request.readyState==4) { requestInProgress = false; if (lastSLVSet) { lastSLVBtn.title = 'Отметить задание как нерешенное'; lastSLVBtn.onclick = function () { setSolved(this, this.guid, false) } lastSLVBtn.onmouseover = function () { this.src = '../../images/chk_in.gif'; } lastSLVBtn.onmouseout = function () { this.src = '../../images/chk.gif'; } lastSLVBtn.src = '../../images/chk.gif'; } else { lastSLVBtn.title = 'Отметить задание как решенное'; lastSLVBtn.onclick = function () { setSolved(this, this.guid, true) } lastSLVBtn.onmouseOver = function () { this.src = '../../images/chk_ds_in.gif'; } lastSLVBtn.onmouseOut = function () { this.src = '../../images/chk_ds.gif'; } lastSLVBtn.src = '../../images/chk_ds.gif'; } lastSLVBtn=null; } } function setFavCnt(cnt) { if (!cnt.match(/^\s*\d+\s*$/)) return; var c = document.getElementById('fav_cnt'); if (c) c.innerHTML = cnt; } setFavCnt('0'); </script> <table border="0" cellpadding="1" cellspacing="1" width="100%"><tr><td width="100%" align="center" class="header" valign="top" height="30">Информационные процессы (0)</td></tr><tr><td height="30" align="center"> </td></tr></table><br> <script language="javascript"> var abort_answer_senging; function onButtonClick() { var aform=document.checkform; abort_answer_senging = false; setAnswer(aform); if (abort_answer_senging) return; ; //aform.submit(); if (aform.setBtn) aform.setBtn.disabled=true; } function onResetClick() { var aform=document.checkform; var aEl = document.createElement('input'); aEl.type = 'hidden'; aEl.name = 'reset'; aEl.value = 1; aform.appendChild(aEl); ; aform.submit(); } function noAction() { } </script> <style type="text/css"> .img_scroll_container { height: 400px; overflow-y: scroll; text-align: center; width:100%;} .img_scroll_container img { width: 700px } .printbody .img_scroll_container { height: auto; overflow-y: hidden; } .printbody .img_scroll_container img { width: 650px } </style> <script language="javascript"> var qguid=''; var qfiles_location='../../'; function ShowPictureQ(s,hint) { while ((p=s.indexOf(". "))>0) s=s.substring(0,p+1)+s.substring(p+2); document.write('<IMG SRC="'+qfiles_location+s+'" ALIGN=ABSMIDDLE alt="'+hint+'" border="0"> '); } function ShowPictureQBL(s,hint,h,bl) { while ((p=s.indexOf(". "))>0) s=s.substring(0,p+1)+s.substring(p+2); var vspace=h/2-bl; if (vspace<0) vspace=-vspace; document.write('<IMG SRC="'+qfiles_location+s+'" ALIGN=MIDDLE border="0" alt="'+hint+'" VSPACE='+(vspace)+' STYLE="position:relative; top:'+(h/2-bl)+'px;">'); } function ShowPictureQ2WH(s,s2,hint,w,h) { if (s.indexOf('.flv')>0 ||s.indexOf('.mp4')>0 ||s.indexOf('.swf')>0) s='../../show_media.php?m='+encodeURIComponent(s)+'&w='+w+'&h='+h; w=w+40; h=h+30; document.write('<a href="javascript:var wnd=window.open(\''+qfiles_location+s+'\',\'\',\',status=1,resizable=1,menubar=0,scrollbars=1,width='+w+', height='+h+',left='+((screen.width-w)/2)+',top='+((screen.height-h)/2)+'\');wnd.focus();"><IMG BORDER=0 SRC="'+qfiles_location+s2+'" ALIGN=ABSMIDDLE style="cursor:pointer" alt="'+hint+'"></a> '); //alert('вставил картинку!'); } function ShowPictureQ3WH(s,s2,s3,hint,w,h) { ShowPictureQ2WH(s,s2,hint,w,h); } function ShowPictureQ2(s,s2,hint) { ShowPictureQ2WH(s,s2,hint,600,400); }; function invertImage(img, s, s2) { if (img.src.indexOf(s)>0) img.src=qfiles_location+s2; else img.src=qfiles_location+s; } function ShowPictureQ3(s,s2,hint) { while ((p=s.indexOf(". "))>0) s=s.substring(0,p+1)+s.substring(p+2); var onclick=(s.indexOf('.jpg')>0||s.indexOf('.png')>0||s.indexOf('.gif')>0 ?'onclick="invertImage(this, \''+s+'\', \''+s2+'\')"':''); document.write('<IMG SRC="'+qfiles_location+s2+'" '+onclick+' ALIGN=ABSMIDDLE style="cursor:pointer" alt="'+hint+'" border="0"> '); }; function showXGraphic(xml) { document.write("<object classid=\"CLSID:A40BD42C-2DF9-4DB6-AE58-6411A05C7827\" ID=GraphX, width=258, height=410 ><param name=DEsignMode value=1><param name=\"Buffer\" value='<?xml version=\"1.0\"?>"+xml+"'></object>"); } /* function ShowPictureQGX2(img,xml) { w=500; h=400; document.write('<IMG BORDER=0 SRC="'+qfiles_location+img+'" ALIGN=ABSMIDDLE>'); } */ function ShowPictureQGX2(img,xml) { w=500; h=400; document.write('<a href="javascript:var wnd=window.open(\'../../showxgprahic.php?qguid='+qguid+'&xml='+xml+'\',\'\',\',status=1,resizable=1,menubar=0,scrollbars=1,width='+w+', height='+h+',left='+((screen.width-w)/2)+',top='+((screen.height-h)/2)+'\');wnd.focus();"><IMG BORDER=0 SRC="'+qfiles_location+img+'" ALIGN=ABSMIDDLE style="cursor:pointer"></a> '); } </script> <table border="0" cellpadding="1" cellspacing="1" width="100%"><tr><td width="100%" align="center" valign="top" height="10"> </td></tr><tr><td height="30"> </td></tr></table></td></tr></table> </td> </tr> </table> <script type="text/x-mathjax-config">MathJax.Hub.Config({messageStyle: "none", "HTML-CSS": { matchFontHeight: true }, MMLorHTML: { prefer: { MSIE: "MML" } } });</script><SCRIPT language=JavaScript src="../../lib/bdetect.js" type=text/javascript></SCRIPT> <script language='JavaScript'> var crtm="1477900079"; function SubmitForm(aform,pgname) { var aEl = document.createElement('input'); if (!browser.isMac || !browser.isIE) aEl.type = 'hidden'; aEl.style.display = 'none'; aEl.name = 'crtm'; aEl.value = crtm; aform.appendChild(aEl); aform.action=pgname; aform.submit(); } function GetPageName(pgname,extparams){ if (pgname=='') pgname='/os/xmodules/qprint/index.php'; if (extparams=='') pgname=pgname+"?crtm="+crtm; else pgname=pgname+"?crtm="+crtm+"&"+extparams; return pgname;} function ShowPage(pgname,extparams,wndname,wndparam){ if (wndname=='') { location.href=GetPageName(pgname,extparams); } else {if (wndparam=='') wnd=window.open(GetPageName(pgname,extparams),wndname); else wnd=window.open(GetPageName(pgname,extparams),wndname,wndparam); wnd.focus();} } </script> </body> </html>
Офлайн
Установил Fiddler и увидел, что перед запросом страницы index.php запрашивается страница qsearch.php. В случае обращения к ней - все работает. Проблема решена
Офлайн