Firstly, there seems to be a consistent error in your code. Take the first loop. You are assigning the text you get out of each node to the same variable. In other words, only the final value is kept, and the rest are thrown away. Is that really what you want? I would expect that either
you should be adding them to a list, or at the least appending them all.
Once you've fixed that, you're right - you can factor out the bits that are the same into a method, with arguments for those things that are different in each case and those things that need to be passed in. For instance, something like: