As a peruvian, I can assure that you can buy the tickets before arriving to the city through the websites listed by @JoErNano or any other you may found on internet.
And additionally, I would suggest you to buy the tickets from well known companies, as OLTURSA (I traveled with this one and it's really comfortable and not so expensive), Cruz del Sur (This is good but a bit expensive), Ormeño, etc
Why? Because not every company is reliable when it comes to puntuality, comfortability, security, etc.
This doesn't mean that you won't suffer of any of this things but is less probable.
You can get cross prices with various of good companies on this link
Ps: Be sure that there is a direct route from where you are to where you want to go, sometimes that there is no direct route and you may need to use some local transports like public taxis , taxi motos, or make connections through differents buses.
Ps2: About @blackbird57 query , I believe that if you buy it on the local currency (soles) there won't be any extra charge, but if you buy it with your own currency (it will be changed as their will) which is probably, because paying through the website is with credit cards, the price may raise a bit. It's always "cheaper" to buy with soles, unless you buy on not so reliable companies which may give you a "gringo" rate.