Como eu faço o resultado disso uma variável?
-
24-09-2019 - |
Pergunta
No momento, está configurado para gravar em um arquivo, mas eu quero que ele produz o valor para uma variável. Não tenho certeza de como.
from BeautifulSoup import BeautifulSoup
import sys, re, urllib2
import codecs
woof1 = urllib2.urlopen('someurl').read()
woof_1 = BeautifulSoup(woof1)
woof2 = urllib2.urlopen('someurl').read()
woof_2 = BeautifulSoup(woof2)
GE_DB = open('GE_DB.txt', 'a')
for row in woof_1.findAll("tr", { "class" : "row_b" }):
for col in row.findAll(re.compile('td')):
GE_DB.write(col.string if col.string else '')
GE_DB.write(" ")
GE_DB.write("\n")
GE_DB.close()
for row in woof_2.findAll("tr", { "class" : "row_b" }):
for col in row.findAll(re.compile('td')):
GE_DB.write(col.string if col.string else '')
GE_DB.write("\n")
GE_DB.close()
Solução
values = []
for row in woof_1.findAll("tr", { "class" : "row_b" }):
for col in row.findAll(re.compile('td')):
if col.string:
values.append(col.string)
result = ''.join(values)
Outras dicas
Livre -se de todas as menções do GE_DB.
Faça um outputtext = ""
no início.
Substituir GE_DB.write(col.string if col.string else '')
com outputtext += col.string if col.string else ''
Talvez assim.
gedb = "";
for row in woof_1.findAll("tr", { "class" : "row_b" }):
for col in row.findAll(re.compile('td')):
if col.string:
gedb += col.string
import cStringIO as StringIO # or import StringIO if on a fringe platform
buf = StringIO.StringIO()
for row in woof_1.findAll("tr", { "class" : "row_b" }):
for col in row.findAll(re.compile('td')):
buf.write(col.string if col.string else '')
result = buf.getvalue()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow