【发布时间】: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