954
社区成员
发帖
与我相关
我的任务
分享
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)) ##就是这个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)
>>> 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);