2014-11-18 2 views
1

안녕하세요 stackoverflow 커뮤니티!파일에 BeautifulSoup 출력을 쓰는 데 문제가 있습니다

저는 여전히 파이썬에서 코딩의 장점과 장점을 배우고 있습니다. 따라서 제 코드를 게시 해 주시기 바랍니다.

현재 BS4를 사용하여 http://kat.ph에서 최신 미디어 급류 목록을 긁어 내 파일로 저장하는 스크립트를 작성하려고합니다. 그러나 BS4의 출력물을이 파일에 인쇄하는 데 문제가 있습니다. 텍스트 파일을 열면 비어 있지만 터미널에서 스크립트를 실행하면 정상적으로 작동합니다. 궁극적으로, 파이썬에서 이메일에 bs4 출력을 보내도록하고 싶습니다. (원래이 문제를 접했고 .txt 파일에 쓸 수 있는지 확인하기로했습니다.)

나는 지금 내 가정용 컴퓨터에서 만든 스크립트가 없지만, 나는 똑같은 일을 한 다른 스크립트를 다시 만들었다.

도움/제안 사항을 보내 주시면 감사하겠습니다. 그래서, 바로 당신의 글을 쓸데 할 수있다 textFile.write(writingFunction()), 당신은 아무것도 반환하지 않습니다

print str(counter) + '.' + ' ' + i.content.replace('\n', '')

def writing_function(): 
    with open('C:/python27/file.txt', 'a') as f: 
     for ind, i in enumerate(soup.find_all('div', {'class': 'markedBlock torType filmType'}),1): 
      f.write("{}. {}".format(ind, i.text.replace("\n",""))) 
각 줄을 인쇄한다 :

from bs4 import BeautifulSoup 
import requests 
import time 

#The goal of this script was to scrape the names of the latest media torrents and write them to a text file. 
#When I run the script on my computer, I can see the prompt give me the list of torrents just fine. 
#When I try to write to a file or send an email, it doesn't print anything. 

req = requests.get('http://kat.ph') 

site = req.text 

soup = BeautifulSoup(site) #Tried making this 'soup = str(BeautifulSoup(site)) to no avail. 

def writingFunction(): 
    #I imported time module because I had my script display the time and date here. 
    counter = 1 
    for i in soup.find_all('div', {'class': 'markeredBlock torType filmType'}): 

     print str(counter) + '.' + ' ' + i.text 
     counter = counter + 1 

textFile = open('C:/python27/file.txt', 'a') 
textFile.write(writingFunction()) #I've tried making this a str and I've also tried assigning the function to a variable 
textFile.close() 

답변

1

단지 현재 당신은 그냥 출력을 인쇄하는 함수에 쓰기 기능. 파일 이름을 하드 코딩하지 않으려면

단지 매개 변수로 전달합니다

def writing_function(my_file): 
    with open(my_file, 'a') as f: 

귀하의 카운터 변수가하고있는 일을 할 것입니다 1의 시작 인덱스 enumerate 사용.

bs4에 .content이 없으며, 텍스트 사용을 원할 경우 contents이 목록입니다. i.text.

+0

유일한 방법은 인쇄하지 않는 것입니다. find_all에서 아무 것도 발견되지 않는 경우입니다. –

+0

작동하지 않는다고 말하면 내게 믿을 수 없습니다. 나는 당신이 말한 것을 따랐으며 열거 기능을 사용했다. – dbakathaillist

+0

당신의 find_all mus는 아무 것도 발견하지 못해서 파일이 비어 있다는 것을 알 수 있습니다. findall의 내용을 실제로 인쇄 해 보았습니까? –

관련 문제