python - How do i get my Beautiful soup output data to a text file? -


how beautiful soup output data text file?
here's code;

import urllib2  bs4 import beautifulsoup  url = urllib2.urlopen("http://link").read()  soup = beautifulsoup(url)  file = open("parseddata.txt", "wb")  line in soup.find_all('a', attrs={'class': 'book-title-link'}):   print (line.get('href'))   file.write(line.get('href'))   file.flush()   file.close() 

file.close should called once (after for loop):

import urllib2 bs4 import beautifulsoup  url = urllib2.urlopen("http://link").read() soup = beautifulsoup(url) file = open("parseddata.txt", "wb") line in soup.find_all('a', attrs={'class': 'book-title-link'}):     href = line.get('href')     print href     if href:         file.write(href + '\n') file.close() 

update can use href=true avoid if statement. in addition it, using with statement, don't need close file object manually:

import urllib2 bs4 import beautifulsoup   content = urllib2.urlopen("http://link").read() soup = beautifulsoup(content)  open('parseddata.txt', 'wb') f:     in soup.find_all('a', attrs={'class': 'book-title-link'}, href=true):         print a['href']         f.write(a['href'] + '\n') 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -