<h2> のテキストは取得できた! しかしリンクを取得する方法がわからない
Pythonを使ったwebスクレイピングで<h2> のテキストとそのリンクをcsvファイルで取得しようとしています。
<h2> のテキストは取得できたのですが、リンク (href) の中身(#id2など)を取得する方法がわかりません。 - スクレイピング対象: [BeautifulSoup4ドキュメント](http://kondou.com/BS4/index.html)望む結果
<h2> のテキストとリンクをcsvファイルで取得 ``` 0,(訳注)石鹸は食べられない¶,#id2 1,この文書について¶,#id3 ...(略) ``` ## <h2> の中身 ```html <h2>(訳注)石鹸は食べられない<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2> <h2>この文書について<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2 ``` 以下のような例もあるし、h2にhrefもあるのでhrefを取得する方法はあるはず。。。と思いつつもこけています。現在for文をひとつ使っているので、その中でリンク取得するのではないかと推測しているのですがうまくいきません(T_T) ```python for link in soup.find_all('a'): print(link.get('href')) ```現在のコード
python
1# -*- coding: utf-8 -*- 2from bs4 import BeautifulSoup 3import requests 4import csv 5 6""" 7csvファイルに<h2>のテキストとリンクを保存したい 8""" 9r = requests.get("http://kondou.com/BS4/index.html") 10soup_content = BeautifulSoup(r.content, "html.parser") 11 12alltxt = soup_content.get_text() 13with open('h2textlink.csv', 'w+',newline='',encoding='utf-8') as f: 14 n = 0 15 for subheading in soup_content.find_all('h2'): 16 sh = subheading.get_text() 17 18 writer = csv.writer(f, lineterminator='\n') 19 writer.writerow([n, sh]) 20 n += 1 21pass
現在の出力結果
0,(訳注)石鹸は食べられない¶ 1,この文書について¶ 2,助けてほしいときは¶ 3,インストール後の問題¶ 4,パーサーのインストール¶ ...(略)
h2のテキストとリンク取得完了!
おかげさまでできました! (≧∀≦)
python
1# -*- coding: utf-8 -*- 2from bs4 import BeautifulSoup 3import requests 4import csv 5 6""" 7csvファイルに<h2>のテキストとリンクを保存 8""" 9r = requests.get("http://kondou.com/BS4/index.html") 10soup_content = BeautifulSoup(r.content, "html.parser") 11 12alltxt = soup_content.get_text() 13with open('h2textlink.csv', 'w+',newline='',encoding='utf-8') as f: 14 writer = csv.writer(f, lineterminator='\n') 15 std_link = 'http://kondou.com/BS4/' 16 for n, subheading in enumerate(soup_content.find_all('h2')): 17 sh = subheading.get_text() 18 h2link = subheading.a['href'] 19 20 writer.writerow([n, sh, std_link + h2link]) 21pass
コード実行結果
csv
10,(訳注)石鹸は食べられない¶,http://kondou.com/BS4/#id2 21,この文書について¶,http://kondou.com/BS4/#id3 32,助けてほしいときは¶,http://kondou.com/BS4/#id5 43,インストール後の問題¶,http://kondou.com/BS4/#id9 5...(略)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/28 09:53
2018/08/28 09:58
2018/08/28 10:17