V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
bestehen
V2EX  ›  Python

Python 里面把字符串变字典,因为经常在抓数据的时候遇到

  •  
  •   bestehen · 2018-07-27 18:01:45 +08:00 · 2055 次点击
    这是一个创建于 2071 天前的主题,其中的信息可能已经有所发展或是发生改变。

    除了用 json.loads 之外 看到网上有人说 eval 但是用的时候总是报错各种 Traceback (most recent call last): File "run.py", line 44, in <module> run().get_spider(sys.argv[1:][0]) File "run.py", line 29, in get_spider news_source().get_odaily_content() File "/home/shenjianlin/my_project/news_source/news_source.py", line 544, in get_odaily_content print(eval(response.text)) File "<string>", line 1, in <module> NameError: name 'null' is not defined 用了就报错!</module></string></module>

    5 条回复    2018-07-29 19:15:41 +08:00
    Atang
        1
    Atang  
       2018-07-27 19:06:27 +08:00
    建议代码格式整理一下。。不然。。。
    rocketman13
        2
    rocketman13  
       2018-07-28 17:16:45 +08:00
    eval 可以将字符串改为字典?
    noqwerty
        3
    noqwerty  
       2018-07-29 04:54:38 +08:00
    可以用 from ast import literal_eval,不过有什么特别的原因不用 json.loads 吗?

    另外你这个报错看着像是返回值并不是 json 格式,只是个 null。
    bestehen
        4
    bestehen  
    OP
       2018-07-29 13:34:46 +08:00
    @noqwerty 我是看看有没有其他的处理方法
    sxd96
        5
    sxd96  
       2018-07-29 19:15:41 +08:00
    eval 还有安全性问题,是什么原因不能用 json.loads 吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1540 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:15 · PVG 01:15 · LAX 10:15 · JFK 13:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.