我是Mysqldb和Python的新手。我设法将所有链接存储到一个表中。现在我想检索这些链接并使用urllib
获取它们。我的代码应该将它们保存到Mysql表中。
import MySQLdb
import urllib
mydb = MySQLdb.connect(
host='localhost',
user='root',
passwd='shailang',
db='urls')
cursor = mydb.cursor()
with open ("s.txt","r") as file:
for line in file:
cursor.execute("INSERT INTO url(links) VALUES(%s)", line)
cursor.execute("SELECT * FROM url")
links = cursor.fetchall()
for row in links:
page = urllib.urlopen(row[0])
text = page.read()
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
在for
循环中,使用row[0]
代替row
。
for row in links:
page = urllib.urlopen(row[0])
text = page.read()
数据库中的一条记录可以有多个值。row
变量是一个元组(包含特定记录的列值),links
变量是一个列表(包含代表记录的元组)。
因为你只有一列,你想要那列的数据,我们需要使用row[0]