I am trying to create a python program which is capable of getting the objects title and its cost from ‘https://coinmarketcap.com/’ website. in this image i have my initial code. I keep getting an error that says:
JavaScript
x
2
1
AttributeError: 'NoneType' object has no attribute 'text'
2
however, both the ‘priceHeading’ & ‘priceValue’ class have values of ‘bitcoin price’ and ‘29,000’ respectively. How do I get those values?
here’s my initial code:
JavaScript
1
19
19
1
# import libraries
2
import urllib.request as ur
3
from bs4 import BeautifulSoup
4
5
quote_page = 'https://coinmarketcap.com/currencies/bitcoin/'
6
7
page = ur.urlopen(quote_page)
8
9
soup = BeautifulSoup(page, 'html.parser')
10
11
name_box = soup.find('h1', attrs={'class': 'priceHeading'})
12
13
name = name_box.text.strip()
14
print (name)
15
16
price_box = soup.find('div', attrs={'class':'priceValue'})
17
price = price_box.text
18
print (price)
19
Advertisement
Answer
You probably received compressed response from the server which urllib.request
cannot handle. Instead of urllib.request
use requests
module:
JavaScript
1
15
15
1
import requests
2
from bs4 import BeautifulSoup
3
4
quote_page = "https://coinmarketcap.com/currencies/bitcoin/"
5
6
soup = BeautifulSoup(requests.get(quote_page).content, "html.parser")
7
name_box = soup.find("h1", attrs={"class": "priceHeading"})
8
9
name = name_box.text.strip()
10
print(name)
11
12
price_box = soup.find("div", attrs={"class": "priceValue"})
13
price = price_box.text
14
print(price)
15
Prints:
JavaScript
1
3
1
Bitcoin Price (BTC)
2
$29,919.86
3