0

Im doing some python web content requests and I want to make some functions in my code, but there is one error and I dont know why it´s showing. My code looks like this:

def tempRequest(tree, heading):

    page = requests.get("http://10.0.0.3/admin/speedtest.php")
    tree = html.fromstring(page.content)
    heading = tree.xpath('//a[@id="temperature"]/text()')
    return heading, tree

    tempRequest(tree, heading)
    heading = tree.xpath('//a[@id="temperature"]/text()')

    sheet = client.open("Database").sheet1

    sheet.insert_row(heading, 10)
    time.sleep(5)

tempRequest(tree, heading) NameError: name 'tree' is not defined

Could you guys please help me? Thanks.

17
  • 1
    Because, on calling the (poorly indented) function, there is no tree in the global scope to pass to the function. How can you pass tree in tempRequest(tree, heading) when it doesn't exist prior to calling the function? Even without knowledge of python scoping, this is illogical. Commented Mar 2, 2019 at 15:57
  • So I should make it like this: page = requests.get("http://10.0.0.3/admin/speedtest.php") tree = html.fromstring(page.content) heading = tree.xpath('//a[@id="temperature"]/text()') tempRequest(tree, heading) Commented Mar 2, 2019 at 16:04
  • You pass values to the call, which are bound to the parameter names inside the function. As written, tempRequest doesn't need any arguments, though. Commented Mar 2, 2019 at 16:06
  • @PetrJelínek I think you're moving towards the right answer but please edit this into the original question so we can see where you're up to Commented Mar 2, 2019 at 16:07
  • 1
    You actually don't. Nice edit, but the answer by ruohola shows how none of these names need to be defined prior to calling the function. You don't have to initialise any variables and get in a chicken-or-egg situation, let the function return the values to define them in the global scope. Commented Mar 2, 2019 at 16:15

1 Answer 1

3

You have some basic mistakes in your code, it should be like this:

def tempRequest():
    page = requests.get("http://10.0.0.3/admin/speedtest.php")
    tree = html.fromstring(page.content)
    heading = tree.xpath('//a[@id="temperature"]/text()')
    return heading, tree

heading, tree = tempRequest()
sheet = client.open("Database").sheet1

sheet.insert_row(heading, 10)
time.sleep(5)

In your original code you're trying to pass variables to the function before you have defined them in your code. And you're not using your functions return values at all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.