Reputation: 315
So I am trying to create a script where I have two function where the first function I send a requests and save two values and the second function is where I apply it as a json. Before I continue my issue I would like to add my code:
def get_info(thread):
url = thread #Whatever site such as Google.com
headers = {
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Pragma': 'no-cache',
'Cache-Control': 'max-age=0',
}
r = requests.get(url, headers=headers, timeout=12)
bs4 = soup(r.text, "html.parser") #We scrape here
try:
search = bs4.find('h1').text
except:
search = None
try:
image = bs4.find('image')
except:
image = None
#I want to use the search and image on the function below
--------------------------------------------------------- #Here is where I want to cut
def get_json():
url = thread + '.json' #We just add json at the end to get the website that supports json
headers = {
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Pragma': 'no-cache',
'Cache-Control': 'max-age=0',
}
r = requests.get(url, headers=headers, timeout=12)
json_resp = r.json()
for i in json_resp:
if search in i['search']: #I use the 'search = bs4.find('h1').text' to match and only want to print if it matches
print(i)
try:
final_name = i['name']
except:
final_name = None
try:
final_img = i['image']
except:
final_img = None
metadata = {
'name': final_name,
'image': final_img
}
return metadata #return the value
There is two function get_info
and get_json
- What I want to do is that when I run the code:
while True:
testing = get_json(thread)
print(testing)
time.sleep(5)
an output should be return of get_json
- However the issue I am having is that I want to only call get_json(thread)
but to be able to get a return of get_json(thread)
I need to get the value of search from get_info(thread)
only ONCE (its the same all the time) to be ablet o continue to run the get_json(thread)
My question is: How can I be able to call get_json(thread)
without needing to call get_info(thread)
for everytime I call get_json(thread)
(To gain the search value from get_info(thread)
only once and use it everytime I call get_json)
Upvotes: 0
Views: 36
Reputation: 911
If get_info()
return value does not change, you could call it once before entering while loop and pass the return value of get_info()
as a parameter to get_json()
along with thread
Upvotes: 1