I sent a request to a website and then parsed it. Got a list but have issues making it a csv file table. When I try this:
from bs4 import BeautifulSoup
import requests
import csv
website = requests.get("https://www.tradingview.com/markets/cryptocurrencies/prices-all/")
soup = BeautifulSoup(website.text, 'lxml')
name = soup.find_all('a', class_ ="tv-screener__symbol")
with open('newparser.csv', 'w') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(name)
It prints out:
"<a class=""tv-screener__symbol"" href=""/markets/cryptocurrencies/prices-cryptoxtvcbtc/"" target=""_blank"">Bitcoin</a>","<a class=""tv-screener__symbol"" href=""/markets/cryptocurrencies/prices-cryptoxtvceth/"" target=""_blank"">Ethereum</a>","<a class=""tv-screener__symbol"" href=""/markets/cryptocurrencies/prices-cryptoxtvcbnb/"" target=""_blank"">Binance Coin</a>","<a class=""tv-screener__symbol"" href=""/markets/cryptocurrencies/prices-cryptoxtvcada/"" target=""_blank"">Cardano</a>","<a class=""tv-screener__symbol"" href=""/markets/cryptocurrencies/prices-cryptoxtvcusdt/"
Not going to post the whole thing but you get the point.
When I change:
wr.writerow(name) --> wr.writerow(name.text)
It prints out:
ResultSet object has no attribute 'text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
And when I make a loop:
for i in name:
wr.writerow(i.text)
It creates a file like this:
"B","i","t","c","o","i","n"
"E","t","h","e","r","e","u","m"
"B","i","n","a","n","c","e"," ","C","o","i","n"
"C","a","r","d","a","n","o"
"T","e","t","h","e","r"
"H","E","X"
"X","R","P"
"S","o","l","a","n","a"
"D","o","g","e","c","o","i","n"
"U","S","D"," ","C","o","i","n"
"P","o","l","k","a","d","o","t"
"T","e","r","r","a"
"U","n","i","s","w","a","p"
How do I fix this?
CodePudding user response:
writerow
takes an iterable to columns.
Strings are iterable, causing each character to be put into columns
If you want to write a single value, then put a list around the value
for i in name:
writer.writerow([i.text])