如何从表中检索行,并使用urllib获取/打开每个链接



我是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]

最新更新