-1

I am looking at the link for the song Blank Space by Taylor Swift. I am trying to isolate just the number of views. But I can't seem to get it to use as a number.

This is what it returns:

Taylor Swift - Blank Space - YouTube
[u'721,891,621']

It isn't really a number, because I get this error if I add a 1:

print pizza[0].contents +1
TypeError: can only concatenate list (not "int") to list

Here is the code.

from bs4 import BeautifulSoup
import urllib2

url="https://www.youtube.com/watch?v=e-ORhEE9VVg"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
print unicode(soup.title.string)


pizza= soup.find_all("div",{"class","watch-view-count"})
print pizza[0].contents
user2859603
  • 235
  • 4
  • 9
  • 18
  • It says it in the exception: `can only concatenate list to list`. Therefore `pizza[0].contents` is a list. – grovesNL Apr 05 '15 at 21:55
  • Where are you using `soup.find()`? You are using `soup.find_all()` then accessed an attribute one of results. The [`.content` attribute documenation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children) tells you what type it is: a `list` object. – Martijn Pieters Apr 05 '15 at 22:05

1 Answers1

1

pizza[0].contents is a list. It says it directly in the exception you encountered. This can be verified by checking type(pizza[0].contents)

If you are trying to use the first element of the lists, use the indexer as you did for pizza: pizza[0].contents[0]. You can verify the type of this element by checking type(pizza[0].contents[0])

If you need an integer, you can do the appropriate conversions afterwards. There are several methods to convert your text to an integer when it has commas for thousands separators.

Community
  • 1
  • 1
grovesNL
  • 6,016
  • 2
  • 20
  • 32
  • The line: "print pizza[0].contents[0]" Returns the following error: "TypeError: an integer is required" The line: I was hoping I could isolate the just the string. Then I could use the method you suggested to make it an integer. – user2859603 Apr 05 '15 at 22:39
  • The line:"type(pizza[0].contents[0])" returns the value "" – user2859603 Apr 05 '15 at 22:45
  • 1
    @user2859603: That is a BeautifulSoup type. [So now you can refer to the documentation to convert it to a unicode string.](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring) Note the comment about calling `unicode` on that type: `unicode(pizza[0].contents[0])` – grovesNL Apr 05 '15 at 22:51