2016-05-14 2 views
-1

これで、bs4(BeautifulSoup)を使用してウェブサイトを解析し、探している特定のタイトルを探しています。bs4を使用してテキスト上の空白を取り除く方法

import requests 
from bs4 import BeautifulSoup 
url = 'http://www.ewn.co.za/Categories/Local' 
r = requests.get(url).text 
soup = BeautifulSoup(r) 
for i in soup.find_all(class_='article-short'): 
    if i.a: 
     print(i.a.text.replace('\n', '').strip()) 
    else: 
     print(i.contents[0].strip()) 

このコードは動作しますが、出力には、それはウェブサイトから要求されたタイトルを印刷する前に、最初の空白の20行のように示しています。私のコードは次のようになります。私のコードに何か間違いがあるのですか、空白を取り除くために何かできるのでしょうか?

+0

あなたは(https://docs.python.org/3/library/stdtypes.html#str.strip) – Querenker

答えて

0

あなたはこのような要素を持っているので:

<article class="article-short"> 
<div class="thumb"><a href="http://ewn.co.za/2016/05/14/Contralesa-against-scrapping-initiation-due-to-cold-weather"><img alt="FILE: Boys who have undergone a circumcision ceremony walk near Qunu in the Eastern Cape in 2013. Picture: AFP." height="147" src="http://ewn.co.za/cdn/-%2fmedia%2f3C37CB28056746CD95FC913757AAD41C.ashx%3fas%3d1%26h%3d147%26w%3d234%26crop%3d1;waeb9b8157b3e310df" width="234"/></a></div> 
<h6 class="h6-mega"><a href="http://ewn.co.za/2016/05/14/Contralesa-against-scrapping-initiation-due-to-cold-weather">Contralesa against scrapping initiation due to cold weather</a></h6> 
</article> 

最初のリンクは、画像やテキストなしが含まれています。

おそらくh6タグを探してください。だから、このようなものは動作します:

import requests 
from bs4 import BeautifulSoup 
url = 'http://www.ewn.co.za/Categories/Local' 
r = requests.get(url).text 
soup = BeautifulSoup(r) 
for i in soup.find_all(class_='article-short'): 
    title = (i.h6.text.replace('\n', '') if i.h6 else contents[0]).strip() 
    if title: 
     print(title) 
+0

おかげで、文字列に空白文字を削除することができ、ストリップ機能で! @ aldanorそれは今より良く機能します! – raid3r

関連する問題