NameError: name 're' is not defined

エラー

問題発生したコード

 状態:-  閲覧数:861  投稿日:2017-10-15  更新日:2017-10-15  
▼index.py
from urllib.request import urlopen
from bs4 import BeautifulSoup
from bottle import route, view

@route('/')
@view("index_template")
def index():
   html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon")
   internalLinks=[]
   bsObj = BeautifulSoup(html, "html.parser")
   for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!.)*$")):
       if 'href' in link.attrs:
           internalLinks.append(link.attrs['href'])
   return dict(internalLinks=internalLinks)



エラーメッセージ


Apacheログ
▼/var/log/httpd/
[error]     for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$")):
[error] NameError: name 're' is not defined


エラー対応


「import re」追加
・Pythonで正規表現を使用するためには、「re」ライブラリーを読み込む必要がある


修正後コード


from urllib.request import urlopen
from bs4 import BeautifulSoup
from bottle import route, view
import re

@route('/')
@view("index_template")
def index():
   html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon")
   internalLinks=[]
   bsObj = BeautifulSoup(html, "html.parser")
   for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!.)*$")):
       if 'href' in link.attrs:
           internalLinks.append(link.attrs['href'])
   return dict(internalLinks=internalLinks)



urllib.error.HTTPError: HTTP Error 403: Forbidden

IndentationError: unexpected indent

コメント投稿(ログインが必要)