2017-07-18 12 views
0

おそらく非常に具体的な質問ですが、私は以下のコードを使用してテキストの一部を取り除くのに苦労しています。私は、「クラス」の下に「p」というタグを見つけることで見つけることができる普通の記事のテキストを必要とします: 'mol-para-with-font'。どういうわけか、私は著者のバイライン、日付スタンプ、そして最も重要なのはページの広告からのテキストのようなものをたくさん入手します。 htmlを調べると、同じ「クラス」を含んでいるそれらを見ることができません:「mol-para-with-font」なので私は困惑しています(または多分私はあまりにも長くそれを見つめていました...)。私はあなたの助けに感謝しますので、ここにhtmlの達人がたくさんいることを知っています。Beautifulsoup:不要な部分を除外します

私のコード:class="mol-para-with-font"

import requests 
import translitcodec 
import codecs 

def get_text(url): 
    r = requests.get(url) 
    soup = BeautifulSoup(r.content, "lxml") 

    # delete unwanted tags: 
    for s in soup(['figure', 'script', 'style', 'table']): 
     s.decompose() 

    article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all(['p', {'class':'mol-para-with-font'}])]  
    article = '\n'.join(article_soup) 

    text = codecs.encode(article, 'translit/one').encode('ascii', 'replace') #replace traslit with ascii 
    text = u"{}".format(text) #encode to unicode 
    print text 

url = 'http://www.dailymail.co.uk/femail/article-4703718/How-Alexander-McQueen-Kate-s-royal-tours.html' 
get_text(url) 

答えて

1

のみ'p' -s? これはあなたにそれを与える:

import requests 
from bs4 import BeautifulSoup as BS 
url = 'http://www.dailymail.co.uk/femail/article-4703718/How-Alexander-McQueen-Kate-s-royal-tours.html' 
r = requests.get(url) 
soup = BS(r.content, "lxml") 

for i in soup.find_all('p', class_='mol-para-with-font'): 
    print(i.text) 
+0

ありがとう。私は今、私はあまりにも多くの括弧などで奪われていることがわかります:) – aviss

関連する問題