2017-02-21 8 views
0

これはしばらくの間作業していましたが、多分私は必要な答えを得るために間違ったことを探しています。htmlを変更してhtml文書を保存する

私はウェブページで検索したい特定の単語をキーとする辞書を持っています。私はそれらの単語を強調表示し、結果のHTMLをローカルファイルに保存したいと思います。

EDIT:後で、人々は自分自身でコードを実行するようになりました。このlinkには、単語辞書と、私がスキャンしているページの中で最も一致するはずのコードをテストするために使用しているページのHTMLが含まれています。代わりに、実際のwebsiteを使用することもできます。リンクはコード内のrl [0]を置き換えます。

try: 
     #rl[0] refers to a specific url being pulled from a list in another file. 
     req = urllib.request.Request(rl[0],None,headers) 
     opener = urllib.request.build_opener(proxy_support, urllib.request.HTTPCookieProcessor(cj)) 
     resp = opener.open(req) 
     soup = BeautifulSoup(resp.read(),'html.parser') 
     resp.close 
    except urllib.error.URLError: 
     print("URL error when opening "+rl[0]) 
    except urllib.error.HTTPError: 
     print("HTTP error when opening "+rl[0]) 
    except http.client.HTTPException as err: 
     print(err, "HTTP exception error when opening "+rl[0]) 
    except socket.timeout: 
     print("connection timedout accessing "+rl[0]) 
     soup = None 
    else: 
     for l in [wdict1,wdict2,wdict3,wdict4]: 
      for i in l: 
       foundvocab = soup.find_all(text=re.compile(i)) 
       for term in foundvocab: 
        #c indicates the highlight color determined earlier in the script based on which dictionary the word came from. 
        #numb is a term i defined earlier to use as a reference to another document this script creates. 
        fixed = term.replace(i,'<mark background-color="'+c+'">'+i+'<sup>'+numb+'</sup></mark>') 
        term.replace_with(fixed) 
     print(soup, file=path/local.html) 

私が抱えている問題は、スープが印刷されると、見つかった各単語の段落全体が印刷され、強調表示されないということです。代わりに私は言うことができる:

foundvocab = soup.find_all(text=i) 

と結果のHTMLファイルは空白です。

答えて

0

ok。以下のコードは私が必要とするものを見つけて置き換えます。今私はちょうど別の問題であるより大きいとより小さいシンボルを表示する問題があります。見て回る時間を惜しまなかった人に感謝します。

foundvocab = soup.findAll(text=re.compile('{0}'.format(i)), recursive=True) 
    for fw in foundvocab: 
     fixed_text = fw.replace('{0}'.format(i), '<mark background-color="'+c+'">'+i+'<sup>'+numb+'</sup></mark>') 
     fw.replace_with(fixed_text) 
関連する問題