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

标签 python urllib mysql-python

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

关于python - 如何从表中检索行并使用 urllib 获取/打开每个链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990467/

相关文章:

python - 创建日志文件

python - Pywinauto:找不到 click() 方法

python - 使用 np.select 使用多索引数据帧创建新列

python - 如何访问用于 python 中的 urllib 模块的字典值?

python - 使用 "tornado.httpclient"获取 "POST https"站点获取 "HTTPError: HTTP 599"

python - 为什么我在使用 urllib2 请求 URL 时得到 “HTTP Error 405: Method Not Allowed”?

python - 类型错误 : 'connection' object is not callable in python using mysqldb

Python:如何将所有 'for loop' 输出作为一个变量解析到 mysql 更新查询

python - 如何在 python 3.6 中加载在 python 3.5 上训练的机器学习模型?

python - 如何设置连接mysql数据库的时间限制