首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python db。Errno 9坏文件描述符

Python db。Errno 9坏文件描述符
EN

Stack Overflow用户
提问于 2013-10-28 21:05:55
回答 1查看 7K关注 0票数 4

长话短说,我试图从网站上读取HTML,并将表的值放在本地MySQL数据库中。我成功地使用BeautifulSoup4从表中删除了所有信息,但在将其放入MySQL db时遇到了困难。

我使用的是与Python2.7.5兼容的mysql.connector。这是我的代码:

代码语言:javascript
复制
import urllib2
from bs4 import BeautifulSoup
import mysql.connector
from mysql.connector import errorcode

# Opens MySQL db and handles all connection errors
dbConfig = {'user':'root',
            'password':'pimovi',
            'host':'127.0.0.1',
            'database':'RateYourMusic'}
try:
    db = mysql.connector.connect(**dbConfig)
    cursor = db.cursor()
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print "Something is wrong with your user name or password"
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print "Database does not exist"
    else:
        print err
else:
    db.close()

url = 'http://rateyourmusic.com/customchart'
req = urllib2.Request(url, headers={'User-Agent':'Mozilla/5.0'})
read = urllib2.urlopen(req)
soup = BeautifulSoup(read)

table = soup.find('table', {'class':'mbgen'})

for row in table.findAll('tr'):
    try:
        cells = row.findAll('td')
        rank = int(cells[0].find(class_='ooookiig').text)
        artist = cells[2].find(class_='artist').text
        album = cells[2].find(class_='album').text
        year = cells[2].find(class_='mediumg').text
        year = int(year[1:5])

        entry = {'Rank':rank, 'Artist':artist, 'Album':album, 'Year':year}
        add_album = ("INSERT INTO chartinfo "
                     "(rank_info, artist_info, album_info, year_info) "
                     "VALUES (rank, artist, album, year)")
        cursor.execute(add_album)
        db.commit()
        print entry
    except AttributeError:
        pass

cursor.close()
db.close()

评论-ed的回溯

代码语言:javascript
复制
Traceback (most recent call last): 
File "C:\Programming\RateYourMusicCrawler\AlbumInfoCrawler.py", line 52, in <module> 
    cursor.execute(add_album) 
File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 393, in execute
    self._handle_result(self._connection.cmd_query(stmt)) 
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 586, in cmd_query 
    statement)) 
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 386, in _send_cmd 
    packet_number) 
File "C:\Python27\lib\site-packages\mysql\connector\network.py", line 104, in send_plain
    raise errors.OperationalError(str(err)) 
mysql.connector.errors.OperationalError: [Errno 9] Bad file descriptor
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-28 21:30:47

这可能是因为:

代码语言:javascript
复制
else:
    db.close()

如果try块不导致任何异常,则关闭连接。试着把它拿出来。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19645074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档