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
phantomer
V2EX  ›  Python

python scrapy 爬一个网站的,遇到了中文链接,存入不了数据库,你们是咋样解决的??、

  •  
  •   phantomer · 2016-06-03 15:37:51 +08:00 · 4142 次点击
    这是一个创建于 2895 天前的主题,其中的信息可能已经有所发展或是发生改变。

    scrapy 爬一个网站,如:http://xxx.org/,遇到了一个链接是 http://xxx.org/新闻,

    发现这个链接,在 scrpay print 话能输出到 shell 里,在 scrapy shell 里用 sel.xpath("//@href"),也能筛选到,但是在入 mysql 的时候,只能存入这个中文链接前的 url 链接,这个是 python2 的 unicode 问题么?

    def parse(self, response):
        conn = MySQLdb.connect(host="localhost",user="root",passwd="root",db="url")
        cur = conn.cursor()
        for sel in response.xpath('//@href').extract():
                x = sel
                cur.execute('insert into urlsinfo (url) values(%s)',x)
                conn.commit()
        cur.close()
    

    代码略丑,勿喷。 刚学习 scrapy ,你们都是怎么解决这个问题的?

    11 条回复    2016-06-03 18:03:32 +08:00
    phantomer
        1
    phantomer  
    OP
       2016-06-03 15:39:17 +08:00
    入库前用 base64 encode 了也无法存入数据库。
    fengxiang
        2
    fengxiang  
       2016-06-03 15:51:14 +08:00
    charset=‘ utf8 ’
    annielong
        3
    annielong  
       2016-06-03 16:01:05 +08:00
    或者是 mysql 插入时候有问题,貌似插入中文的时候也要设置编码的
    besttime
        4
    besttime  
       2016-06-03 16:04:03 +08:00
    感觉是数据库的问题, mysql 使用之前默认编码改了吗?没改就肯定了。别怪 python 哦。
    WangYanjie
        5
    WangYanjie  
       2016-06-03 16:23:58 +08:00
    是数据库的问题吧
    phantomer
        6
    phantomer  
    OP
       2016-06-03 16:27:59 +08:00
    @fengxiang
    @annielong
    @besttime
    @WangYanjie
    数据库设置的是 utf-8
    fengxiang
        7
    fengxiang  
       2016-06-03 16:29:56 +08:00   ❤️ 1
    你要告诉 python 用 utf-8 操作数据库
    MySQLdb.connect(host="localhost",user="root",passwd="root",db="url", charset=‘ utf8 ’)
    phantomer
        8
    phantomer  
    OP
       2016-06-03 16:33:10 +08:00
    @fengxiang 我试试看。
    whnzy
        9
    whnzy  
       2016-06-03 16:41:32 +08:00
    try: except 把错误报出来
    phantomer
        10
    phantomer  
    OP
       2016-06-03 17:51:39 +08:00
    @fengxiang 感谢帮我解决了问题,结贴了。
    mactaew
        11
    mactaew  
       2016-06-03 18:03:32 +08:00
    PHPer 一眼想到的是 urlencode() 和 urldecode() 。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1240 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:08 · PVG 07:08 · LAX 16:08 · JFK 19:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.