我正在尝试使用python和数据库来显示一系列信息。但是,我的输出只显示最后一列。我知道我的意思表达得不是很清楚。因此,我将代码和输出放在下面:现在输出显示如下:
$ python pricewatch.py
Harvey Norman Site Search
iPad 2 Wi-Fi 16GB Black
iPad 2 Wi-Fi 16GB
iPad mini Wi-Fi + Cellular 32GB
iPad mini Wi-Fi 16GB
iPad mini Wi-Fi + Cellular 64GB
iPad Wi-Fi 64GB with Retina Display
iPad Wi-Fi 32GB with Retina Display
iPad 2 Wi-Fi 16GB White
iPad 2 Wi-Fi + 3G 16GB
iPad Wi-Fi + Cellular 32GB with Retina Display
iPad mini Wi-Fi + Cellular 16GB
$357
$697
$756
$647
$395
$545
$777
$487
(8, u'iPad mini Wi-Fi + Cellular 16GB', u'Harvey Norman Site Search', u'$487')//如您所见,它只显示我的代码的最后一个
url="http://m.harveynorman.com.au/computers/tablets-readers/ipads"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
sitename=soup.find('label',{'for':'search'})
print sitename.renderContents()
productname=soup.findAll('strong',{'class':'name fn'})
for eachproductname in productname:
print eachproductname.renderContents()
productprice=soup.findAll('span',{'class':'price'})
for eachproductprice in productprice:
print eachproductprice.renderContents().replace("<span>","").replace("</span>","")
conn =sqlite3.connect('pricewatch.db')
c = conn.cursor()
c.execute("CREATE TABLE if not exists table1 (id integer, name text, store text, price real)")
eachname = eachproductname.renderContents()
eachprice = eachproductprice.renderContents().replace("<span>","").replace("</span>","")
sitename = sitename.renderContents()
assignnumber = randint(1,30) #issue here,want to assign a series of number by the scriptself
data = [(assignnumber,eachname,sitename,eachprice),
]
c.executemany('INSERT INTO table1 VALUES (?,?,?,?)',data)
#output
for row in c.execute('select * from table1'):
print row现在,我想要的数据库输出如下(1,ipadXX,HN,$199) (2,ipad xx,NH,$200) .....
希望任何人可以给我的提示或编辑我的脚本。
向余航致敬
发布于 2013-05-31 20:59:14
没有什么问题:
for row in c.execute('select * from table1'):
print row只需确保您首先提交插入:
c.executemany('INSERT INTO table1 VALUES (?,?,?,?)',data)
conn.commit()然后,您仍然可以逐个提取记录,而不是像fetchall()那样一次检索所有行。
发布于 2013-05-31 20:50:32
应该在execute之后调用fetchall
for row in c.execute("select * from table1").fetchall():
print(row)发布于 2013-05-31 21:27:53
@jon Clements是对的,你的问题在这里:
data = [(assignnumber,eachname,sitename,eachprice),
]这需要在一个循环中--现在只给它分配了第一组值,这就是要插入的所有值。
编辑
好的,所以你想要这样的东西:
for (name, price) in zip(productname, productprice):
name_data = name.renderContents()
price_data = price.renderContents().replace() # fill in your replacements here
site_data = sitename.renderContents()
assign_number = random.randint(1,30)
c.execute('insert into table1 values (?,?,?,?)',
(name_data, price_data, site_data, assign_name))https://stackoverflow.com/questions/16857372
复制相似问题