|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 cc9200 于 2017-3-6 21:24 编辑
win7
python 3.5
postgresql 9.3
- import urllib.request
- import re
- import psycopg2 as psy
- conn=psy.connect(database='test1',user='postgres',password='091297',host='127.0.0.1',port='5432')
- cur=conn.cursor()
- try:
- cur.execute('create table 糗事百科(num int,str text);')
- except:
- pass
- conn.commit()
- def get_html(url):
- req = urllib.request.Request(url)
- req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:43.0) Gecko/20100101 Firefox/43.0')
- response=urllib.request.urlopen(req)
- html=response.read().decode('utf-8')
- return html
- def get_list(html):
- list1=re.findall(r'\<div class="content"\>\n{4}.+?\n{3}\</div\>',html)
- for each in list1:
- str1=re.search(r'\<span\>.+\</span\>',each).group()[6:-7]
- str1=str1.replace('<br/>','\n')
- print(str1)
- global i
- i=i+1
- print(i)
- cur.execute('''insert into 糗事百科 values(%d,%s);'''%(i,str1))
- conn.commit()
- i=0
- for page in range(1,35):
- print(page)
- html=get_html('http://www.qiushibaike.com/text/page/'+str(page)+'/')
- get_list(html)
复制代码
以上是完整代码,千万别复制过去运行啊,你没有psycopg2这个库,而且还需要postgresql数据库
- >>> cur.execute('insert into 糗事百科 values(%d,%s);'%(1,'1234'))
- >>> cur.execute('insert into 糗事百科 values(%d,%s);'%(1,'12,34'))##一个逗号的差别
- Traceback (most recent call last):
- File "<pyshell#12>", line 1, in <module>
- cur.execute('insert into 糗事百科 values(%d,%s);'%(1,'12,34'))
- psycopg2.ProgrammingError: 错误: INSERT 的表达式多于指定的字段数
- LINE 1: insert into 糗事百科 values(1,12,34);
复制代码
问题就出在,字符串里面的逗号上,其实是字符串里面的逗号,不是分隔符。其实是一个数据,不是用逗号分隔成的两个
一个字符串作为变量传入SQL语句,没办法再改成三引号啥的
如果提问提的不清楚,请指教
本帖最后由 不二如是 于 2017-3-9 14:30 编辑
不要用中文输入的“,”
要用英文的","
下面的02行
cur.execute('insert into 糗事百科 values(%d,%s);'%(1,'"12,34"'))##一个逗号的差别
|
|