2017-05-22 18 views
0
from urllib.request import urlopen 
from bs4 import BeautifulSoup 

#specify the url 
wiki = "http://www.bbc.com/urdu" 

#Query the website and return the html to the variable 'page' 
page = urlopen(wiki) 


#Parse the html in the 'page' variable, and store it in Beautiful Soup format 
soup = BeautifulSoup(page,"html.parser") 
all_links=soup.find_all("a") 
for link in all_links: 
    #print (link.get("href")) 
    #text=soup.body.get_text() 
    #print(text) 
    for script in soup(["script", "style"]): 
     script.extract() # rip it out 

# get text 
text=soup.body.get_text() 

# break into lines and remove leading and trailing space on each 
lines = (line.strip() for line in text.splitlines()) 
# break multi-headlines into a line each 
chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 
# drop blank lines 
text = '\n'.join(chunk for chunk in chunks if chunk) 

print(text) 
text1 = str(text) 
text_file = open("C:\\Output.txt", 'w') 
text_file.write(text) 
text_file.close() 

美しいスープを使ってニュースサイトからデータを抽出したいと思います。私はコードを書いたが、それは私に必要な出力を与えていない。まず、ページ内のすべてのリンクを処理してからデータを抽出し、ファイルに保存する必要があります。それでは、次のページとデータを抽出して保存するなど...今は、最初のページでリンクを処理しようとしていただけですが、フルテキストは表示されず、出力にいくつかのタグが付いています。beautifulsoupを使ってデータを抽出

data = [] 
soup = BeautifulSoup(page,"html.parser") 
for link in soup.find_all('a', href=True): 
    data.append(link['href']) 

text = '\n'.join(data) 
print(text) 

し、ファイルにテキストを保存するために進ん:あなたはこのような何かを試すことができ、ウェブサイトからのすべてのリンクを抽出するために

答えて

0

。その後、dataを繰り返して、それらのウェブサイトのすべてのURLを取得する必要があります。

+0

返信いただきありがとうございますが、これはlinks.iを抽出するだけで、すべてのリンクからテキストを抽出します。 – user3778289

関連する問題