Форум сайта python.su
Здравствуйте вытащил js код странницы нужно через регулярное выражение получить массив вида
. Вот js код:
<script type="text/javascript"> var transl_next_page='Следующая страница'; var prevLink = true; var nextLink = true; var nextChapterLink = "/noblesse/vol8/473"; // var ads = "" var servers = ['http://e4.postfact.ru/','http://e2.postfact.ru/','http://e3.postfact.ru/','http://e5.postfact.ru/','http://e1.postfact.ru/','http://e6.postfact.ru/','http://e7.postfact.ru/','http://e8.postfact.ru/']; function sendExternalSize(divH, w) { } function sendURL(path) { } rm_h.init( [['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_00.png_res.jpg",690,703],['auto/22/58','http://e7.postfact.ru/',"/42/Noblesse_ch471_01.png_res.jpg",690,19200],['auto/22/58','http://e5.postfact.ru/',"/42/Noblesse_ch471_02.png_res.jpg",690,19200],['auto/22/58','http://e2.postfact.ru/',"/42/Noblesse_ch471_03.png_res.jpg",690,18748],['auto/22/58','http://e8.postfact.ru/',"/42/Noblesse_ch471_04.png_res.jpg",690,20765],['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_05.png_res.jpg",690,17600],['auto/22/58','http://e3.postfact.ru/',"/42/Noblesse_ch471_06.png_res.jpg",690,10522]], 0, false); </script>
from bs4 import BeautifulSoup import os, requests def readmanga(url, download=0, filename=False): name1 =url.split('/')[2] r = requests.get(url) soup = BeautifulSoup(requests.get(url).text, 'lxml') name = 'MANGA'+os.sep+name1+os.sep+soup.find('span', {'class': 'name'}).text aray1 = soup.find('table', {'class': 'table table-hover'}).find_all('a') aray=[] for link in aray1: aray.append('http://'+name1+link.get('href')) soup = BeautifulSoup(requests.get(aray[1]).text, 'lxml') aray1 = soup.find_all('script', {'type': 'text/javascript'})[8] print(aray1)
Отредактировано prisrak_razyma (Сен. 3, 2017 21:19:10)
Офлайн
prisrak_razyma
Здравствуйте вытащил js код странницы нужно через регулярное выражение получить массив вида
s = ''' var transl_next_page='Следующая страница'; var prevLink = true; var nextLink = true; var nextChapterLink = "/noblesse/vol8/473"; // var ads = "" var servers = ['http://e4.postfact.ru/','http://e2.postfact.ru/','http://e3.postfact.ru/','http://e5.postfact.ru/','http://e1.postfact.ru/','http://e6.postfact.ru/','http://e7.postfact.ru/','http://e8.postfact.ru/']; function sendExternalSize(divH, w) { } function sendURL(path) { rm_h.init( [['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_00.png_res.jpg",690,703],['auto/22/58','http://e7.postfact.ru/',"/42/Noblesse_ch471_01.png_res.jpg",690,19200],['auto/22/58','http://e5.postfact.ru/',"/42/Noblesse_ch471_02.png_res.jpg",690,19200],['auto/22/58','http://e2.postfact.ru/',"/42/Noblesse_ch471_03.png_res.jpg",690,18748],['auto/22/58','http://e8.postfact.ru/',"/42/Noblesse_ch471_04.png_res.jpg",690,20765],['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_05.png_res.jpg",690,17600],['auto/22/58','http://e3.postfact.ru/',"/42/Noblesse_ch471_06.png_res.jpg",690,10522]], 0, false); } ''' import re bad_pattern = re.compile(r'var\s+(?P<name>[a-zA-Z_]+)\s?=\s?(?P<value>[^;]+);') matches = bad_pattern.findall(s) print(matches) import slimit from slimit.parser import Parser from slimit.visitors import nodevisitor from slimit import ast parser = Parser() tree = parser.parse(s) print("Collect all arrays from a piece of JS-code") for node in nodevisitor.visit(tree): if isinstance(node, ast.Array): try: print("An array was found:", list(map(lambda x: x.value, node.items))) except AttributeError: pass
Офлайн
prisrak_razyma
Может быть я скажу какую-то глупость, но почему бы не выдернуть нужные данные с помощью JS? C-eval -ить всю эту портянку и всего делов.
Офлайн
scidamЗдравствуй вот код
def readmanga(url, download=0, filename=False): name1 =url.split('/')[2] r = requests.get(url) soup = BeautifulSoup(requests.get(url).text, 'lxml') name = 'MANGA'+os.sep+name1+os.sep+soup.find('span', {'class': 'name'}).text aray1 = soup.find('table', {'class': 'table table-hover'}).find_all('a') aray=[] for link in aray1: aray.append('http://'+name1+link.get('href')) soup = BeautifulSoup(requests.get(aray[1]).text, 'lxml') aray1 = soup.find_all('script', {'type': 'text/javascript'})[8] # print(aray1) s = str(aray1) import re bad_pattern = re.compile(r'var\s+(?P<name>[a-zA-Z_]+)\s?=\s?(?P<value>[^;]+);') matches = bad_pattern.findall(s) print(matches) import slimit from slimit.parser import Parser from slimit.visitors import nodevisitor from slimit import ast parser = Parser() tree = parser.parse(s) print("Collect all arrays from a piece of JS-code") for node in nodevisitor.visit(tree): if isinstance(node, ast.Array): try: print("An array was found:", list(map(lambda x: x.value, node.items))) except AttributeError: pass
WARNING: Couldn't write lextab module <module 'slimit.lextab' from 'G:\\pyton\\lib\\site-packages\\slimit\\lextab.py'>. Won't overwrite existing lextab module
WARNING: yacc table file version is out of date
WARNING: Token 'LINE_COMMENT' defined, but not used
WARNING: Token 'BLOCK_COMMENT' defined, but not used
WARNING: Token 'LINE_TERMINATOR' defined, but not used
WARNING: Token 'CLASS' defined, but not used
WARNING: Token 'CONST' defined, but not used
WARNING: Token 'ENUM' defined, but not used
WARNING: Token 'EXPORT' defined, but not used
WARNING: Token 'EXTENDS' defined, but not used
WARNING: Token 'IMPORT' defined, but not used
WARNING: Token 'SUPER' defined, but not used
WARNING: There are 10 unused tokens
WARNING: Couldn't create <module 'slimit.yacctab' from 'G:\\pyton\\lib\\site-packages\\slimit\\yacctab.py'>. Won't overwrite existing tabmodule
Traceback (most recent call last):
File "G:\парсер\1.py", line 2, in <module>
com.readmanga('http://readmanga.me/noblesse')
File "G:\парсер\comiks.py", line 28, in readmanga
tree = parser.parse(s)
File "G:\pyton\lib\site-packages\slimit\parser.py", line 93, in parse
return self.parser.parse(text, lexer=self.lexer, debug=debug)
File "G:\pyton\lib\site-packages\ply\yacc.py", line 331, in parse
return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
File "G:\pyton\lib\site-packages\ply\yacc.py", line 1199, in parseopt_notrack
tok = call_errorfunc(self.errorfunc, errtoken, self)
File "G:\pyton\lib\site-packages\ply\yacc.py", line 193, in call_errorfunc
r = errorfunc(token)
File "G:\pyton\lib\site-packages\slimit\parser.py", line 116, in p_error
self._raise_syntax_error(token)
File "G:\pyton\lib\site-packages\slimit\parser.py", line 89, in _raise_syntax_error
self.lexer.prev_token, self.lexer.token())
File "<string>", line None
SyntaxError: Unexpected token (LT, '<') at 1:0 between None and LexToken(ID,'script',1,1)
Отредактировано prisrak_razyma (Сен. 4, 2017 11:21:54)
Офлайн
prisrak_razymaЧто нужно получить? Напиши входные данные, которые поступают; выходные данные, которые должны быть получены из входных данных.
через регулярное выражение получить массив вида
Офлайн
py.user.next
входные данные (пример):
<script type="text/javascript"> var transl_next_page='Следующая страница'; var prevLink = true; var nextLink = true; var nextChapterLink = "/noblesse/vol8/473"; // var ads = "" var servers = ['http://e4.postfact.ru/','http://e2.postfact.ru/','http://e3.postfact.ru/','http://e5.postfact.ru/','http://e1.postfact.ru/','http://e6.postfact.ru/','http://e7.postfact.ru/','http://e8.postfact.ru/']; function sendExternalSize(divH, w) { } function sendURL(path) { } rm_h.init( [['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_00.png_res.jpg",690,703],['auto/22/58','http://e7.postfact.ru/',"/42/Noblesse_ch471_01.png_res.jpg",690,19200],['auto/22/58','http://e5.postfact.ru/',"/42/Noblesse_ch471_02.png_res.jpg",690,19200],['auto/22/58','http://e2.postfact.ru/',"/42/Noblesse_ch471_03.png_res.jpg",690,18748],['auto/22/58','http://e8.postfact.ru/',"/42/Noblesse_ch471_04.png_res.jpg",690,20765],['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_05.png_res.jpg",690,17600],['auto/22/58','http://e3.postfact.ru/',"/42/Noblesse_ch471_06.png_res.jpg",690,10522]], 0, false); </script>
['auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_00.png_res.jpg",'auto/22/58','http://e7.postfact.ru/',"/42/Noblesse_ch471_01.png_res.jpg",'auto/22/58','http://e5.postfact.ru/',"/42/Noblesse_ch471_02.png_res.jpg",['auto/22/58','http://e2.postfact.ru/',"/42/Noblesse_ch471_03.png_res.jpg",'auto/22/58','http://e8.postfact.ru/',"/42/Noblesse_ch471_04.png_res.jpg",'auto/22/58','http://e6.postfact.ru/',"/42/Noblesse_ch471_05.png_res.jpg",'auto/22/58','http://e3.postfact.ru/',"/42/Noblesse_ch471_06.png_res.jpg"]
Отредактировано prisrak_razyma (Сен. 4, 2017 11:18:44)
Офлайн
Я так понял, нижнюю строку тебе надо, и почистить её ещё немного.
Так и сделай, в несколько этапов: на первом этапе удали всё, кроме нужной строки; на втором этапе оставшуюся строку очисти от ненужных символов в начале и в конце; на третьем этапе удали из неё все числа и запятые; на четвёртом этапе оставшиеся подстроки раздели и занеси в список друг за другом.
Для каждого этапа делаешь функцию, которая принимает такую-то строку, а возвращает такую-то строку. И из функции в функцию передаёшь начальный текст и он у тебя постепенно очищается, пока в конце не превращается в список чистых строк.
То есть твоя ошибка в том, что ты пытаешься сделать всё сразу в одну строку кода. Это неправильно, нужно делать функции и по ним распределять отвественность за каждый кусочек обработки. Каждая функция отвечает за свою часть очистки.
У тебя получится такая цепочка вызовов:
out = f4(f3(f2(f1(text))))
Отредактировано py.user.next (Сен. 4, 2017 12:02:56)
Офлайн
prisrak_razymaЭта ошибка от того, что открывающего и закрывающего тэгов “<script>” не должно быть в строке, которую подаем на парсер.
SyntaxError: Unexpected token (LT, ‘<’) at 1:0 between None and LexToken(ID,'script',1,1)
Офлайн
py.user.next
сделал так
from bs4 import BeautifulSoup import os, requests, function def readmanga(url, download=0, filename=False): name1 =url.split('/')[2] r = requests.get(url) soup = BeautifulSoup(requests.get(url).text, 'lxml') name = 'MANGA'+os.sep+name1+os.sep+soup.find('span', {'class': 'name'}).text aray1 = soup.find('table', {'class': 'table table-hover'}).find_all('a') aray=[] for link in aray1: aray.append('http://'+name1+link.get('href')) soup = BeautifulSoup(requests.get(aray[1]).text, 'lxml') aray1 = soup.find_all('script', {'type': 'text/javascript'})[8].text hav=['rm_h.init( [[','], 0, false);','"',']','[',"'",','] change=['','',"'",'','','',' '] mass=function.poisk(aray1,'m_h.init')[0] print(mass) for i in range(len(hav)): print(hav[i]) mass.replace(hav[i],change[i]) print(mass)
def poisk(text,pois): w=[] if(type(text)==str): mass=text.split('\n') for x in mass: if(x.find(pois,0,len(x))>-1): w.append(x) if (len(w)>0): return w else: return False else: return 'нет функции для этого типа переменной'
Отредактировано prisrak_razyma (Сен. 4, 2017 15:54:58)
Офлайн
scidam
спасибо но я нашел другой способ
Офлайн