2017-04-12 7 views
0

私はWebCrawlingの初心者です。複数のURLのクロールに関する質問があります。Pythonのニュース見出しと内容のウェブクローズの例

私は自分のプロジェクトでCNBCを使用しています。ホームページからニュースのタイトルとURLを抽出したいし、各URLからニュース記事の内容をクロールしたいと思う。

import requests 
from lxml import html 
import pandas 

url = "http://www.cnbc.com/" 
response = requests.get(url) 
doc = html.fromstring(response.text) 

headlineNode = doc.xpath('//div[@class="headline"]') 
len(headlineNode) 

result_list = [] 
for node in headlineNode : 
    url_node = node.xpath('./a/@href') 
    title = node.xpath('./a/text()') 
    soup = BeautifulSoup(url_node.content) 
    text =[''.join(s.findAll(text=True)) for s in soup.findAll("div", {"class":"group"})] 
    if (url_node and title and text) : 
     result_list.append({'URL' : url + url_node[0].strip(), 
          'TITLE' : title[0].strip(), 
          'TEXT' : text[0].strip()}) 
print(result_list) 
len(result_list) 

私はthat'listコンテンツ 『」オブジェクトが属性を持っていません』というエラーを取得し続けています:

これは私がこれまで持っているものです。各見出しのタイトル、各見出しのURL、各見出しのニュース記事の内容を含む辞書を作成したいと考えています。これに簡単にアプローチできますか?

+1

あなたのURLはcnbcのWebアドレスを含む文字列なので、.contentプロパティがないことは驚くことではありません。たぶんあなたはurl_code.contentですか? – Bemmu

+0

@Bemmuはまだ動作しませんが、私は質問を編集しました! – Elizabeth

+0

コンテンツを保護するjsがない – cph

答えて

2

スクリプトの素晴らしいスタートです。ただし、soup = BeautifulSoup(url_node.content)は間違っています。 url_contentはリストです。完全なニュースURLを作成し、HTMLを取得してBeautifulSoupに渡す要求を使用する必要があります。

とは別に、私が見てしまういくつかあります:私は、インポートの問題を参照してください

  1. は、BeautifulSoupはインポートされません。 from bs4 import BeautifulSoupを先頭に追加します。あなたはパンダを使っていますか?そうでない場合は、取り外します。

  2. url_node = node.xpath('./a/@href')を照会すると、大きなバナー画像を持つCNNのニュースディレクターの中には、長さが0のリストが表示されます。これらのニュースURLを取得するには、適切なロジックとセレクタを見つける必要があります。私はあなたにそれを残します。

チェックこのアウト:

import requests 
from lxml import html 
import pandas 
from bs4 import BeautifulSoup 

# Note trailing backslash removed 
url = "http://www.cnbc.com" 
response = requests.get(url) 
doc = html.fromstring(response.text) 

headlineNode = doc.xpath('//div[@class="headline"]') 
print(len(headlineNode)) 

result_list = [] 
for node in headlineNode: 
    url_node = node.xpath('./a/@href') 
    title = node.xpath('./a/text()') 
    # Figure out logic to get that pic banner news URL 
    if len(url_node) == 0: 
     continue 
    else: 
     news_html = requests.get(url + url_node[0]) 
     soup = BeautifulSoup(news_html.content) 
     text =[''.join(s.findAll(text=True)) for s in soup.findAll("div", {"class":"group"})] 
     if (url_node and title and text) : 
      result_list.append({'URL' : url + url_node[0].strip(), 
           'TITLE' : title[0].strip(), 
           'TEXT' : text[0].strip()}) 
print(result_list) 
len(result_list) 

ボーナスデバッグのヒント:

火災アップipython3シェルと%run -d yourfile.pyを行います。 ipdbとデバッグコマンドを参照してください。あなたの変数が何で、正しい方法を呼んでいるかを確認することは非常に役に立ちます。

幸運。

関連する問題