将List存储到Python Sqlite3中



我正在尝试使用Beautiful Soup像这样刮窗体字段id

 for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('input')):
    if link.has_key('id'):
        print link['id']

让我们假设它返回类似

的东西
username
email
password
passwordagain
terms
button_register

我想把这个写进Sqlite3数据库。

我将在我的应用程序中做的是…使用这些表单字段的id并尝试进行POST操作。问题是……有很多这样的网站,我已经刮掉了它们的表单字段id。所以关系是这样的…

Domain1 - First list of Form Fields for this Domain1
Domain2 - Second list of Form Fields for this Domain2
.. and so on
我不确定的是……我应该如何为这种目的设计我的专栏?如果我只创建一个有两列的表,比如 ,可以吗?
COL 1 - Domain URL (as TEXT)
COL 2 - List of Form Field IDs (as TEXT)
有一件事要记住是……在我的应用程序中,我需要做这样的事情…

If Domain is "http://somedomain.com":
    For ever item in the COL2 (which is a list of form field ids):
         Assign some set of values to each of the form fields & then make a POST request

请指路好吗?

编辑于22/07/2011 -是我下面的数据库设计正确吗?

我已经决定有一个这样的解决方案。你们怎么看?

我将有三个表如下

表1

Key Column (Auto Generated Integer) - Primary Key
Domain as TEXT

样本数据应该是这样的:

1   http://url1.com
2   http://url2.com
3   http://url3.com
表2

Domain (Here I will be using the Key Number from Table 1)
RegLink - This will have the registeration link (as TEXT)
Form Fields (as Text)

样本数据应该是这样的:

1   http://url1.com/register    field1
1   http://url1.com/register    field2
1   http://url1.com/register    field3
2   http://url2.com/register    field1
2   http://url2.com/register    field2
2   http://url2.com/register    field3
3   http://url3.com/register    field1
3   http://url3.com/register    field2
3   http://url3.com/register    field3
表3

Domain (Here I will be using the Key Number from Table 1)
Status (as TEXT)
User (as TEXT)
Pass (as TEXT)

样本数据应该是这样的:

1   Pass    user1   pass1
2   Fail    user2   pass2
3   Pass    user3   pass3

你觉得这个桌子设计好吗?或者有什么可以改进的地方?

您的表有一个规范化问题。

使用2个表
TABLE domains
int id primary key
text name
TABLE field_ids
int id primary key
int domain_id foreign key ref domains
text value

正确的数据库设计建议您有一个URL表和一个字段表,每个字段都引用一个URL记录。但是,根据您想对它们做什么,您可以将列表打包到单个列中。查看文档了解如何操作。

sqlite是必需的吗?这可能不是存储数据的最佳方式。例如,如果您需要按URL进行随机访问查找,那么shelve模块可能是更好的选择。如果您只需要记录它们并遍历站点,那么将它们存储为CSV可能更简单。

尝试这样获取id:

ids = (link['id'] for link in
        BeautifulSoup(content, parseOnlyThese=SoupStrainer('input')) 
         if link.has_key('id'))

这将向您展示如何保存、加载它们,以及如何对每个文件执行操作。它使用单个表,并且为每个域的每个字段只插入一行。这是最简单的解决方案,并且完全适合于相对较少的数据行。

from itertools import izip, repeat
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''create table domains
(domain text, linkid text)''')
domain_to_insert = 'domain_name'
ids = ['id1', 'id2']
c.executemany("""insert into domains
      values (?, ?)""", izip(repeat(domain_to_insert), ids))
conn.commit()
domain_to_select = 'domain_name'
c.execute("""select * from domains where domain=?""", (domain_to_select,))
# this is just an example
def some_function_of_row(row):
    return row[1] + ' value'
fields = dict((row[1], some_function_of_row(row)) for row in c)
print fields
c.close()

最新更新