2017-12-30 37 views
0

私はPythonとBeautifulSoupでウェブサイトをスクラップする方法を学ぼうとしています。私はすべての名前/役職を集めることができましたが、私はそれらをCSVファイルに保存しようとしています。私はcsvファイルにそれらをすべて取り込むために、何らかのタイプのループを必要とするか、または追加する必要があります。今のところ、CSVファイルには最終的な名前と役職のみが保存されます。BeautifulSoupのfind_allでウェブサイトからcsvにデータを保存する

#import libraries 
import csv 
import urllib2 
from bs4 import BeautifulSoup 

#specify the url 
buzzly_page = 'http://buzzlymedia.com/ourwork/' 

#query the website and return the html to the variable 'page' 
page = urllib2.urlopen(buzzly_page) 

#parse the html 
soup = BeautifulSoup(page, 'html.parser') 

#query to get value of name 
for name_box in soup.find_all('strong', attrs={'itemprop': 'name'}): 
    name = name_box.text.strip() #remove starting and trailing 
    print name 

#query to get value of job-title 
for job_box in soup.find_all('span', attrs={'itemprop': 'jobTitle'}): 
    job = job_box.text.strip() #remove starting and trailing 
    print job 

#write into csv-file 
with open('buzzly_clients.csv', 'a') as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerow([name, job]) 

答えて

0

希望する要素を含むdivを見つけて、このように繰り返します。

# import libraries 
import csv 
import urllib2 
from bs4 import BeautifulSoup 

# specify the url 
buzzly_page = 'http://buzzlymedia.com/ourwork/' 

# query the website and return the html to the variable 'page' 
page = urllib2.urlopen(buzzly_page) 

# parse the html 
soup = BeautifulSoup(page, 'html.parser') 

# write into csv-file 
with open('buzzly_clients.csv', 'a') as csv_file: 
    writer = csv.writer(csv_file) 

    for div in soup.find_all('div', attrs={'class': 'avia-testimonial-meta-mini'}): 
     # query to get value of name 
     name_box = div.find('strong', attrs={'itemprop': 'name'}) 
     name = name_box.text.strip() # remove starting and trailing 
     print (name) 

     # query to get value of job-title 
     job_box = div.find('span', attrs={'itemprop': 'jobTitle'}) 
     job = job_box.text.strip() # remove starting and trailing 
     print (job) 

     writer.writerow([name, job]) 
関連する問題