2017-01-30 6 views
-4

nbcnews.comからストーリーを抽出しようとしています。私は現在、次のコードを持っている:私は、スクリプトを実行するとBeautifulSoupを使ってPythonでニュース記事を入手する

import urllib2 
from bs4 import BeautifulSoup 

# The page that I'm getting stories from 
url = 'http://www.nbcnews.com/' 

data = urllib2.urlopen(url) 

soup = BeautifulSoup(data, 'html.parser') 

#This is the tag and class that chrome told me "top stories" are stored in 
this = soup.find_all('div', attrs={"class": "col-sm-6 col-md-8 col-lg-9"}) 

#Get the a tags in the previous tag (this is the part that returns FAR too many links 

link = [a for i in this for a in i.find_all('a')] 

#Get the titles (This works) 
title = [a.get_text() for i in link for a in i.find_all('h3')] 

#The below strips all newlines and tabs from the title name 
newtitle = [] 

for i in t: 
    s = ' '.join(i.split()) 
    if s in newtitle: 
     pass 

    else: 
     newtitle.append(s) 

print len(link) 
print len(title) 

、「タイトル」リストには、サイトのタイトル名のわずかな変化(それは近いかどうタイトル名は問題ではありませんと(主に)正しいです

私の問題は、「リンク」リストにはすべてのリンクが含まれているようですか?誰かがこれで私を助けることができますか?

可能であれば、これに類似したAPIがありますか?もし私がそれを避けることができれば、私は本当にニュース記事を入手するために車輪を再発明しないだろう。

EDITは:問題のWebページを見てみると、変数名

答えて

1

にタイプミスを変更し、それがすべてnewstoriesがクラスitem-headingh3タグであるように見えます。あなたは、すべての物語のヘッダを選択し、HTMLツリーに上向きにステップし、それらが中に含まれているa hrefにアクセスするためにBeautifulSoupの.parentメソッドを使用するためにBeautifulSoupを使用することができます。

In [54]: [i.parent.attrs["href"] for i in soup.select('a > h3.item-heading')] 
Out[55]: 
[{'href': '/news/us-news/civil-rights-groups-fight-trump-s-refugee-ban-uncertainty-continues-n713811'}, 
{'href': '/news/us-news/protests-erupt-nationwide-second-day-over-trump-s-travel-ban-n713771'}, 
{'href': '/politics/politics-news/some-republicans-criticize-trump-s-immigration-order-n713826'}, 
... # trimmed for readability 
] 

私はリスト内包を使用していますしましたあなたはリンクのリストを持っていたら、あなたは最初の文字がローカルリンクではなく、外部のリンクだけにマッチする/であるかどうかを確認するために、それを反復処理でき

# select all `h3` tags with the matching class that are contained within an `a` link. 
# This excludes any random links elsewhere on the page. 
story_headers = soup.select('a > h3.item-heading') 

# Iterate through all the matching `h3` items and access their parent `a` tag. 
# Then, within the parent you have access to the `href` attribute. 
list_of_links = [i.parent.attrs for i in story_headers] 

# Finally, extract the links into a tidy list 
links = [i["href"] for i in list_of_links] 

:複合の手順に出て分割することができます。

+0

私は基本的なWebページをBS4で使いこなしてきましたが、HTMLに追いついた後、より複雑なページをナビゲートしようとしました。あなたに+1してください。私を助けてくれてありがとう。これにより、私の音声アシスタントに素敵な追加ができます。あなたが間違ったものにリンクされていれば良いニュース記事は何ですか? ;) – Jebby

+0

あなたは大歓迎です。あなたの問題を解決した場合は、この回答を受け入れてください。ありがとう:) –

+0

私は現時点では家ではないので、私はコードをテストすることはできません。私が家に帰ると私はテストします、それがうまくいくなら私は答えを受け入れます。 – Jebby

関連する問題