コード from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup def getTitle(url): try: html = urlopen(url) except HTTPError: return None try: bs=BeautifulSoup(html.read(),'html.parser') title =bs.body.h1 except AttributeError: return title title = getTitle('http://www.pythonscraping.com/pages/page1.html') if title ==None: print('Title cloud not be found') else: print(title)
このコードを動かすと ⇨ Title cloud not be found
と帰ってくるのですが、
<h1>An Interesting Title</h1>url = 'http://www.pythonscraping.com/pages/page1.html' html = urlopen(url) bs = BeautifulSoup(html.read(),'html.parser') title = bs.body.h1 title
このようにするとtitleを取得できるのですが、
上の関数を使うとなぜかNoneが返されて Title cloud not be found と
表示されていると思っているのですが、という事はHTTPErrorが発生したという事なのでしょうか?
発生しているのなら、なぜ後者では、titleを取得できたのでしょうか?
わかりにくいかと思いますがどなたか回答お願いします。
言語名 python3.7
回答3件
あなたの回答
tips
プレビュー