Python3で、URLを検索して、本のタイトルとURLを取得するプログラムをつくっています。
しかし、aタグのhref属性を取得しようとすると以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
KeyError Traceback (most recent call last)
<ipython-input-128-e3b594fa8210> in <module>()
10 a_list = bs.select("h3")
11 for a in a_list:
---> 12 href= a.attrs['href']
13 text = a.string
14 # aタグのhref属性を取得
KeyError: 'href'
### 該当のソースコード python3.x import requests from bs4 import BeautifulSoup URLからHTMLを取得 url = input("Urlを入力してください: ") response = requests.get(url) response.encoding = response.apparent_encoding bs = BeautifulSoup(response.text, 'html.parser') a_list = bs.select("h3") for a in a_list: href= a.attrs['href'] text = a.string print(text,href) ### 試したこと 本やWebを検索し、aタグに含まれるhref情報を得るためのコードを試してみたのですが、エラーとなり前に進めなくなってしまいました。お手数をお掛けしますが、お教えいただけないでしょうか。 ### 補足情報(取得しようとするWebページのCSSセレクタ) (#main > div > div > section:nth-child(3) > div.row > div.col-sm-9.col-right > div > div.table-responsive > table > tbody > tr:nth-child(1) > td:nth-child(2) > h3 > a)
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/09 06:20