简体   繁体   中英

Python3 requests - cut response

How can i cut the output from a response using Python requests? The output looks like:

...\'\n});\nRANDOMDATA\nExt.define...

or

...\'\n});\nOTHERRANDOMDATA\nExt.define...

And i only want to print out the RANDOMDATA.

req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)

You can use the re module findall() function for searching all occurrences of a regular expression in a string. The following code, just search for the string RANDOMDATA in the response got from requests.get() function

import re
req = "https://example.org/endpoint"
response = requests.get(req, verify=False)

print (response.content)
ar = re.findall('RANDOMDATA',str(response.content))
if len(ar):
    print(ar[0])

This link would be helpful to learn about regular expressions

Additionally, if you have a variable data containing a string to b searched, and a variable t containing a string to search, you can use,

import re
arr = re.findall(t,data)

To return all the occurrences of t in data and:

arr = data.find(t)

To get the index of the first occurrence of t in data

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