【问题标题】:Variables don't pass from main function to other functions变量不会从主函数传递到其他函数
【发布时间】:2020-12-15 11:27:11
【问题描述】:

我正在尝试构建一个网络爬虫。我制作了一个返回 cookie 和标头的函数。为简单起见,我的代码示例是一个常量值,我只设置标头,但通常它会通过请求获取值。另一个函数从网站获取图像链接,但为此它需要标题。我在我的主函数上定义了标题,然后我调用了 get_photos 函数,但它说标题没有定义。

import requests
from bs4 import BeautifulSoup as bs
s = requests.session()

def login():
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0'}
    return headers

def get_photos():
    response = requests.get('https://upload.wikimedia.org/wikipedia/en/thumb/a/a9/Example.jpg/111px-Example.jpg', headers=headers)
    return response

def main():
    """That's where the magic happens."""
    headers = login()
    print(get_photos())

if __name__ == "__main__":
    main()

我得到的错误是:

Traceback (most recent call last):
  File "/home/archie/evip/example.py", line 19, in <module>
    main()
  File "/home/archie/evip/example.py", line 16, in main
    print(get_photos())
  File "/home/archie/evip/example.py", line 9, in get_photos
    response = requests.get('https://upload.wikimedia.org/wikipedia/en/thumb/a/a9/Example.jpg/111px-Example.jpg', headers=headers)
NameError: name 'headers' is not defined

【问题讨论】:

  • 当然,get_photos 范围内的任何地方都没有 headers。最简单的方法是将headers 作为参数传递给get_photos

标签: python function oop beautifulsoup


【解决方案1】:

您需要将 headers 变量传递给get_photos(headers)

import requests
from bs4 import BeautifulSoup as bs
s = requests.session()

def login():
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0'}
    return headers

def get_photos(headers):
    response = requests.get('https://upload.wikimedia.org/wikipedia/en/thumb/a/a9/Example.jpg/111px-Example.jpg', headers=headers)
    return response

def main():
    """That's where the magic happens."""
    print(get_photos(login()))

if __name__ == "__main__":
    main()

【讨论】:

    【解决方案2】:

    您可以修改您的代码以使 headersget_photos 方法的范围内

    import requests
    from bs4 import BeautifulSoup as bs
    s = requests.session()
    
    def login():
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0'}
        return headers
    
    def get_photos(headers):
        response = requests.get('https://upload.wikimedia.org/wikipedia/en/thumb/a/a9/Example.jpg/111px-Example.jpg', headers=headers)
        return response
    
    def main():
        """That's where the magic happens."""
        headers = login()
        print(get_photos(headers))
    
    if __name__ == "__main__":
        main()
    

    检查main中的get_photos方法调用。


    这是由于scope of variables.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-21
      • 2015-07-20
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      相关资源
      最近更新 更多