python-无法找到使用函数从mysql打印数据的想法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-无法找到使用函数从mysql打印数据的想法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2553字,纯文字阅读大概需要4分钟。
内容图文
我已经在python中创建了一个脚本,该脚本能够从网页收集数据并将其存储到mysql中.将数据正确插入mysql后,我的脚本可以在控制台中打印它们.
我的问题是:如何将以下三行包装在单独的函数中并打印存储中的数据?
mycursor.execute("SELECT * FROM webdata")
for item in mycursor.fetchall():
print(item)
我的完整剧本:
import mysql.connector
from bs4 import BeautifulSoup
import requests
URL = "https://www.tripadvisor.com.au/Restaurants-g255068-c8-Brisbane_Brisbane_Region_Queensland.html"
def get_info(link):
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "123",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("DROP TABLE if exists webdata")
mycursor.execute("CREATE TABLE if not exists webdata (name VARCHAR(255), bubble VARCHAR(255), review VARCHAR(255))")
response = requests.get(link)
soup = BeautifulSoup(response.text,"lxml")
for items in soup.find_all(class_="shortSellDetails"):
name = items.find(class_="property_title").get_text(strip=True)
bubble = items.find(class_="ui_bubble_rating").get("alt")
review = items.find(class_="reviewCount").get_text(strip=True)
mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (%s,%s,%s)",(name,bubble,review))
mydb.commit()
#I wish to use the follwing three lines within another function to do the same
mycursor.execute("SELECT * FROM webdata")
for item in mycursor.fetchall():
print(item)
if __name__ == '__main__':
get_info(URL)
解决方法:
我的评论旨在描述此更改后的代码:
import mysql.connector
from bs4 import BeautifulSoup
import requests
# This is a new function
def do_fetch (cursor):
cursor.execute("SELECT * FROM webdata")
for item in cursor.fetchall():
print(item)
URL = "https://www.tripadvisor.com.au/Restaurants-g255068-c8-Brisbane_Brisbane_Region_Queensland.html"
def get_info(link):
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "123",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("DROP TABLE if exists webdata")
mycursor.execute("CREATE TABLE if not exists webdata (name VARCHAR(255), bubble VARCHAR(255), review VARCHAR(255))")
response = requests.get(link)
soup = BeautifulSoup(response.text,"lxml")
for items in soup.find_all(class_="shortSellDetails"):
name = items.find(class_="property_title").get_text(strip=True)
bubble = items.find(class_="ui_bubble_rating").get("alt")
review = items.find(class_="reviewCount").get_text(strip=True)
mycursor.execute("INSERT INTO webdata (name,bubble,review) VALUES (%s,%s,%s)",(name,bubble,review))
mydb.commit()
# This part is changed (moved to new function):
do_fetch (mycursor)
if __name__ == '__main__':
get_info(URL)
内容总结
以上是互联网集市为您收集整理的python-无法找到使用函数从mysql打印数据的想法全部内容,希望文章能够帮你解决python-无法找到使用函数从mysql打印数据的想法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。