2016-12-03 6 views
-1

Я пытаюсь извлечь и напечатать URLs и их название (между <a href='url' title='smth'>NAME</a> существующей в HTML файл (сохраненный в диске) без с помощью BeautifulSoup .. или другая библиотека только Python код начинающего Желаний формат печати:Extract URL и их имена HTML-файл, сохраненный на диске и распечатать их соответственно - Python

http://..filepath/filename.pdf 
File's Name 
so on... 

я смог извлечь и распечатать все адреса или имена всех исключительно, но я не добавить все имена, которые следуют через некоторое время в коде, включенном непосредственно перед тегом, и напечатайте их под каждым URL-адресом. Мой код становится беспорядочным, и я довольно сложный. T до сих пор мой код:

import os 
with open (os.path.expanduser('~/SomeFolder/page.html'),'r') as html: 
    txt = html.read() 
# for urls 
nolp = 0 
urlarrow = [] 
while nolp == 0: 
    pos = txt.find("href") 
    if pos >= 0: 
     txtcount = len(txt) 
     txt = txt[pos:txtcount] 
     pos = txt.find('"') 
     txtcount = len(txt) 
     txt = txt[pos+1:txtcount] 
     pos = txt.find('"') 
     url = txt[0:pos] 
     if url.startswith("http") and url.endswith("pdf"): 
      urlarrow.append(url) 
    else: 
     nolp = 1 
for item in urlarrow: 
    print(item) 

#for names 
almost identical code to the above 

html.close() 

Как заставить его работать? Мне нужно объединить их в одну функцию или определить, но как? пс. Я написал ответ ниже, но я думаю, что может быть более простое и решение Pythonic.

ответ

0

Это правильный вывод, который мне нужен, но я уверен, что есть лучший способ.

import os 
with open ('~/SomeFolder/page.html'),'r') as html: 
    txt = html.read() 
    text = txt 
#for urls  
nolp = 0 
urlarrow = [] 
while nolp == 0: 
    pos = txt.find("href") 
    if pos >= 0: 
     txtcount = len(txt) 
     txt = txt[pos:txtcount] 
     pos = txt.find('"') 
     txtcount = len(txt) 
     txt = txt[pos+1:txtcount] 
     pos = txt.find('"') 
     url = txt[0:pos] 
     if url.startswith("http") and url.endswith("pdf"): 
      urlarrow.append(url) 
    else: 
     nolp = 1 

with open (os.path.expanduser('~/SomeFolder/page.html'),'r') as html: 
    text = html.read() 

#for names 
noloop = 0 
namearrow = [] 
while noloop == 0: 
    posB = text.find("title") 
    if posB >= 0: 
     textcount = len(text) 
     text = text[posB:textcount] 
     posB = text.find('"') 
     textcount = len(text) 
     text = text[posB+19:textcount] #because string starts 19 chars after the posB 
     posB = text.find('</') 
     name = text[1:posB] 
     if text[0].startswith('>'): 
      namearrow.append(name) 
    else: 
     noloop = 1 

fullarrow = [] 
for pair in zip(urlarrow, namearrow): 
    for item in pair: 
     fullarrow.append(item) 
for instance in fullarrow: 
    print(instance) 

html.close()