How to only select the nth (42nd) `p` tag with BeautifulSoup?

Viewed 56

I wrote a program that saves the page source from https://www.coinbase.com/price to pyt.txt. How can I parse the price of bitcoin from this text file and have it be printed?

So far, I have learned that the 42nd p tag in the page source is the one that holds the price of bitcoin. So, my code to attempt to extract that value and print it is as follows:

import bs4
file = open('location/pyt.txt', 'r')

soup = bs4.BeautifulSoup(file, 'lxml')
for btc in soup.find_all('p'):
    print(btc[41])

file.close()

When I run it I get the error:

return self.attrs[key]
KeyError: 41

After many hours of YouTubing and googling it seems that BeautifulSoup would work best but I just can't seem to figure it out.

2 Answers

You can use a CSS Selector p:nth-of-type(42), which will select the 42nd <p> tag.

print(soup.select_one('p:nth-of-type(42)'))

btc is not a list or any other data types its a string so if you want to access the 41th p tag in this way, you can append every item to a list then access to the index of the list

Related