LoginSignup
takeshi4
@takeshi4

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

pythonのスクレイピング、requestsモジュールについての質問です。

Q&AClosed

url="https://rtrp.jp/locations/332/categories/291/?order=retrip_score&page={}"

for i in range(1,6):
target_url=url.format(i)
print(target_url)

res=requests.get(target_url)
soup=BeautifulSoup(res.text,'html.parser')

1ページから5ページの内容を全てスクレイピングするにあたって
print(target_url)の時点で1~5ページのURLは取得できるのですが、
requestsモジュールでは5ページ目の情報しか取得できません。
全頁の取得、解析方法をご教示願います。

0

4Answer

ソースコードはマークダウンのコードブロックを使って書いてください。
インデントがなくなっていて、どのインデントレベルで処理しているのか判別できませんので。

以下のコードで全頁取得できているように思えます。

import requests
from bs4 import BeautifulSoup

url = "https://rtrp.jp/locations/332/categories/291/?order=retrip_score&page={}"

for i in range(1,6):
    target_url = url.format(i)
    print(target_url)

    res = requests.get(target_url)
    soup = BeautifulSoup(res.text, 'html.parser')
    for spot in soup.find_all('h3', class_='spotName'):
        print(spot.text.strip())
1

Comments

  1. 回答に書くのではなく、質問を編集してください。
  2. あなたの回答欄に私はコメントすることができませんので、こちらにコメントを書くようにしてください。
    soupの使い方は別途調べてみてください。
    find_all では複数見つかるでしょうから、それぞれに対して text.strip() する必要があります。
    回答のコードを変更しておきました。
  3. 全URLとは何ですか?
    あとは BeautifulSoup の使い方でしょうから、BeautifulSoup について勉強してみてはいかがでしょうか?
    まずは自分で手を動かして、わからないところを質問してください。

失礼しました。

url="https://rtrp.jp/locations/332/categories/291/?order=retrip_score&page={}"

   for i in range(1,6):
   target_url=url.format(i)
   print(target_url)

   res=requests.get(target_url)
   soup=BeautifulSoup(res.text,'html.parser')

以上です。

0

Comments

  1. @takeshi4

    Questioner
    回答ありがとうございます。

    最後の行のコードについてですが、

    soup.findメソッドでは最初のデータしか出力されません。

    しかしfind_allではエラーが発生します。

    全頁全データを出力する方法はございますか?

ありがとうございます。全タイトルを取得できました。
全URLの取得は可能ですか??

0

Your answer might help someone💌