2017-12-30 6 views
0

나는 파이썬과 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]) 
관련 문제