简体   繁体   中英

Python3.7 how to extract numerical value from list

I am doing some CTFs and I made this script:

import requests

page = requests.get("http://ctf.slothparadise.com/about.php").text
p_split = page.split("<p>")
p2_split = p_split[3].split("</p>")

print(p2_split)

My output from this is:

['You are the 135181th visitor to this page.\n      Every thousandth visitor gets a prize.', '\n    </div> <!-- /container -->\n  </body>\n</html>\n']

How can I extract the value 135181 out of this list?

You can try to use regex , this is especially easy since it doesn't seem they change 'th' despite the number ending with 1 or 2:

import re
import requests

page = requests.get("http://ctf.slothparadise.com/about.php").text
re.findall("\d+(?=th)", page)

output:

['135335']

To get this working for any value adapt this:

my_split = ['You are the 135181th visitor to this page.\n      Every thousandth visitor 
gets a prize.', '\n    </div> <!-- /container -->\n  </body>\n</html>\n']

visitor_num = my_split[0].split('You are the ', 1)[1].split('th')[0]
print(visitor_num)

Actually, I can see similar solutions in the comments as well... hope this works for you! For future reference, look up using the split function and indexing- it's something you will definitely use again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM