简体   繁体   English

如何将Beautiful Soup输出保存到我​​的SQLite数据库中?

[英]How do I save Beautiful Soup outputs into my SQLite database?

I have a basic web page running and I have web scraped some temperatures for the week. 我有一个基本的网页正在运行,并且本周网上刮了一些温度。 The output on the page is displaying perfect on the web page. 页面上的输出在网页上显示完美。 I now want to input these into my SQLite3 database. 现在,我想将这些输入到我的SQLite3数据库中。 I've tried finding some tutorials but couldn't find any clear ones. 我试图找到一些教程,但找不到任何清晰的教程。 Can someone guide me on the right path? 有人可以引导我走正确的道路吗?

Thanks in advance. 提前致谢。

def weather_():
page = requests.get("https://www.bbc.co.uk/weather/0/2643743")
soup = BeautifulSoup(page.content, 'html.parser')
today = soup.find('div',{'data-component-id' : 'forecast'})
temp = today.find(class_ = 'wr-day-temperature')
low_temp = (temp.get_text())
return low_temp

I know that this question already has an accepted answer which will work for your purposes, but I just want to mention that you should always use query parameters rather than string formatting to create SQL statements with variables. 我知道这个问题已经有一个可以接受的答案,可以满足您的目的,但是我只想提及您应该始终使用查询参数而不是字符串格式来创建带有变量的SQL语句。 So instead of: 所以代替:

curs.execute("INSERT INTO your_table_name low_temp='{}'".format(low_temp))

You should use: 您应该使用:

curs.execute("INSERT INTO your_table_name low_temp=?", (low_temp,))

The documentation confirms that this is the way to go: 文档确认这是可行的方法:

Usually your SQL operations will need to use values from Python variables. 通常,您的SQL操作将需要使用Python变量中的值。 You shouldn't assemble your query using Python's string operations because doing so is insecure; 您不应该使用Python的字符串操作来汇编查询,因为这样做是不安全的。 it makes your program vulnerable to an SQL injection attack (see https://xkcd.com/327/ for humorous example of what can go wrong). 它使您的程序容易受到SQL注入攻击的影响(有关可能出问题的幽默示例,请参见https://xkcd.com/327/ )。

I realise that for this small example program it's unlikely to make any difference, but it's best to get into good habits. 我意识到,对于这个小的示例程序,不可能有什么区别,但是最好养成良好的习惯。

If you want to just store your low_temp in database, then do a simple SQL insert 如果您只想将low_temp存储在数据库中,则执行简单的SQL插入

import sqlite3

conn = sqlite3.connect('your_database.sqlite3', check_same_thread=False)

curs = conn.cursor()
curs.execute("INSERT INTO your_table_name low_temp='{}'".format(low_temp))
conn.commit()

I recommend you to read some documentation 我建议您阅读一些文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM