2017-10-18 9 views
0

ウェブクロールが初めてで、beautifulsoupをミニプロジェクトに統合する方法を学びたいと思っています。私は彼のyoutube channelのbeautifulsoupに関するthenewbostonのチュートリアルに続いて、Redditからクロールしようとしていました。 Reddit/r/nbaのNBAニュースのタイトルとリンクをクロールしたいが、成功しなかった。ターミナルで返されるのは「終了コード0で処理が完了しました」だけです。私はそれが私の選択と関係していたと感じましたか?どんな指導や助けも大歓迎です。RedditのNBAページをクロールできません

これは、元のコードで動作しませんでした:

import requests 
from bs4 import BeautifulSoup 

def spider(max_pages): 
    page = 1 
    while page <= max_pages: 
     url = 'https://reddit.com/r/nba' + str(page) 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text, "html.parser") 
     for link in soup.find_all('a', {'class': 'title'}): 
      href = link.get('href') 
      print(href) 
     page += 1 

spider(1) 

私はこの方法をやってみましたが、それは問題を解決しませんでした:

import requests 
from bs4 import BeautifulSoup 

def spider(max_pages): 
    page = 1 
    while page <= max_pages: 
     url = 'https://www.reddit.com/r/nba/' + str(page) 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text, "html.parser") 
     for link in soup.findAll('a', {'class': 'title'}): 
      href = "https://www.reddit.com/" + link.get('href') 
      title = link.string 
      print(href) 
      print(title) 
     page += 1 

spider(1) 
+0

リクエストから返された内容を確認しましたか?ボットブロックを回避するには、ユーザーエージェントの文字列を変更する必要があります。 –

+0

アプリケーションを実行すると「プロセスは終了コード0で終了しました」と表示されます – Vincent

+0

plain_textの値は何ですか。 URLパターンも間違っています。 –

答えて

0

は、メインページのタイトルとリンクを取得します。 :

from bs4 import BeautifulSoup 
from urllib.request import urlopen 

html = urlopen("https://www.reddit.com/r/nba/") 
soup = BeautifulSoup(html, 'lxml') 
for link in soup.find('div', {'class':'content'}).find_all('a', {'class':'title may-blank outbound'}): 
    print(link.attrs['href'], link.get_text()) 
+0

これは私のためには機能しませんでした – Vincent

関連する問題