2016-10-15 7 views
0
import requests 
from bs4 import BeautifulSoup 

webpage = requests.get("http://www.nytimes.com/") 
soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") 
for story_heading in soup.find_all(class_="story-heading"): 
articles = story_heading.text.replace('\n', '').replace(' ', '') 
print (articles) 

私のコードがあり、それはウェブサイト上のすべての記事のタイトルのリストを出力します。私は弦を得ます:Python - リストに変換する

見返り:1980 |

ブルックリンファミリ用ルーム付きのスタジオと犬

販売のための家を検索するか、家賃

だから

あなたの家を売る印刷するフィット、私が変換したいおかしい、しかしありませんこれはリスト= ['売り場や家賃を検索する'、 'あなたの家を売る]、...]、魔女は私にrandom.choiceなどのような他の操作をさせてくれるでしょう。
私は試しました:

alist = articles.split("\n") 
print (alist) 

['Back Back:1980 |おかしい、しかし「]

[」ファミリ用ルームと犬とブルックリンメーカー「]

[」販売またはレンタルのための住宅を検索「]

[」売るあなたのホームを印刷するには収まりません']

私が必要とするリストではありません。私は立ち往生している。このコード部分で私を助けてください。

答えて

2

あなたは常にarticlesをあなたのリストの次の値で上書きしています。あなたが代わりにやってみたいことはarticlesリストを作成し、ちょうどappend各反復で:

import requests 
from bs4 import BeautifulSoup 

webpage = requests.get("http://www.nytimes.com/") 
soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") 
articles = [] 
for story_heading in soup.find_all(class_="story-heading"): 
    articles.append(story_heading.text.replace('\n', '').replace(' ', '')) 
print (articles) 

出力は巨大なので、これはそれがどのように見えるかの小さなサンプルです:

['Global Deal Reached to Curb Chemical That Warms Planet', 'Accord Could Push A/C Out of Sweltering India’s Reach ',....] 

さらに、各反復でスペースを削除するだけで済みます。あなたはそれらの置換を行う必要はありません。だから、あなたはあなたの代わりにstory_heading.textでこれを行うことができます。

articles.append(story_heading.text.strip()) 

今、あなたにこのように見て、最終的な溶液を得ることができ、:

import requests 
from bs4 import BeautifulSoup 

webpage = requests.get("http://www.nytimes.com/") 
soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") 
articles = [story_heading.text.strip() for story_heading in soup.find_all(class_="story-heading")] 
print (articles) 
関連する問題