2014-04-05 1 views
0

연구 프로젝트를 위해 온라인 포럼에 하이퍼 링크로 저장된 URL을 모두 저장하려고합니다.BeautifulSoup를 사용하여 csv로 html로 스크랩 URL

내가 '인쇄'할 때 html 스크래핑 결과가 제대로 작동하는 것처럼 보이지만 원하는 모든 URL을 인쇄한다는 의미에서 CSV의 행을 구분할 수 없습니다.

나는 분명히 뭔가 잘못하고있다. 그러나 나는 무엇을 몰라! 그래서 어떤 도움을 주시면 감사하겠습니다.

import urllib2 
from bs4 import BeautifulSoup 
import csv 
import re 

soup = BeautifulSoup(urllib2.urlopen('http://forum.sex141.com/eforum/forumdisplay.php? fid=28&page=5').read()) 

urls = [] 

for url in soup.find_all('a', href=re.compile('viewthread.php')): 
     print url['href'] 

csvfile = open('Ss141.csv', 'wb') 
writer = csv.writer(csvfile) 

for url in zip(urls): 
     writer.writerow([url]) 

csvfile.close() 

답변

1

당신은 urls 목록에 당신의 일치를 추가 해야합니까 : 여기

내가 작성한 코드의

for url in soup.find_all('a', href=re.compile('viewthread.php')): 
    print url['href'] 
    urls.append(url) 

을하고 여기 zip()를 사용할 필요가 없습니다 .

제일 대신 먼저 목록에 수집, 그들을 발견으로 당신의 URL을 쓰기 : 블록이 완료되면

soup = BeautifulSoup(urllib2.urlopen('http://forum.sex141.com/eforum/forumdisplay.php?fid=28&page=5').read()) 

with open('Ss141.csv', 'wb') as csvfile: 
    writer = csv.writer(csvfile) 
    for url in soup.find_all('a', href=re.compile('viewthread.php')): 
     writer.writerow([url['href']]) 

with 문이 당신을 위해 파일 개체를 닫습니다.

+0

감사합니다. 정말 잘되었습니다. – Isak

관련 문제