我正在做一些python web内容请求,我想在我的代码中创建一些函数,但有一个错误,我不知道为什么它显示。我的代码看起来像这样:
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(树,标题)NameError:未定义名称“树”
你能帮我吗?谢谢。
您的代码中存在一些基本错误,它应该是这样的:
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)
在原始代码中,您尝试在代码中定义变量之前将变量传递给函数。并且您根本没有使用函数返回值。