如何解决在python / sqlite3
我正在学习python和sql广告,我在进行此练习时会抓取图书网站。我已经完成了“入门级”的抓取,并将已抓取的数据添加到了数据库中。
我有两个表(类别,书籍),并且我在books表中使用外键与类别表关联
我正在使用for循环来实现将数据写入数据库的操作,但是我无法设置将books表的外键与类别表相关联。
任何帮助!
这是我的代码:
url = "http://books.toscrape.com/index.html"
response = requests.get(url)
soup = BeautifulSoup(response.text,"html.parser")
lists = soup.find_all('ul',{"class":"nav nav-list"})
ordlist = lists[0].find_all('a')
for i in range(1,len(ordlist)): #for loop to loop inside the whole list
category_name = ordlist[i].get_text().strip()
category_url = ordlist[i].get('href')
connection = sqlite3.connect("Books Scraping DataBase.db")
cursor = connection.cursor()
sql = "INSERT INTO Categories (CategoryName,CategoryUrl) VALUES (?,?)"
data = [category_name,category_url]
cursor.execute(sql,data)
connection.commit()
#connection.close()
#print(categorey_list +' --- '+ category_url)
new_url = url.replace("index.html",category_url)
#print(new_url)
response = requests.get(new_url)
soup = BeautifulSoup(response.text,"html.parser")
rows = soup.find_all('li',{'class':'col-xs-6 col-sm-4 col-md-3 col-lg-3'})
print(f'Adding {category_name} Books Category into the Books Scraping DataBase ')
for j in range(len(rows)): #for loop to fetch all books from all categories
h1 = rows[j].find('h3').get_text().split(":")[0]
price = float(rows[j].find('p',{'class' : 'price_color'}).get_text().split('£')[1])
rate = rows[j].find("p").attrs["class"][1]
sql = "INSERT INTO Books (Title,Price,Rating) VALUES (?,?,?)"
data = [h1,price,rate]
cursor.execute(sql,data)
connection.commit()
connection.close()
print('Done')
解决方法
我想我明白了,但是如果有更好的解决方案,我将不胜感激
我在第二个for循环之前添加了此代码
row_id = cursor.lastrowid
这样,我可以将类别ID存储在row_id中,并在第二个for循环中使用它,将其分配为该类别中的书的外键
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。