将列表存储到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
有人能指导我一下吗?
编辑于2011年7月22日 - 我下面的数据库设计正确吗?
我决定采用这样的解决方案。你们觉得怎么样?
我将有三个表,像下面这样:
表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
你觉得这个表的设计好吗?或者有什么可以改进的地方吗?
3 个回答
1
你的表格存在一个规范化的问题。
使用两个表格来处理
TABLE domains
int id primary key
text name
TABLE field_ids
int id primary key
int domain_id foreign key ref domains
text value
会是一个更好的解决方案。
0
试试这个来获取ID:
ids = (link['id'] for link in
BeautifulSoup(content, parseOnlyThese=SoupStrainer('input'))
if link.has_key('id'))
接下来,这段代码应该能告诉你如何保存这些ID,加载它们,并对每个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()