【发布时间】:2019-04-03 23:15:06
【问题描述】:
我在 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)
【问题讨论】:
-
也许我不明白这个问题的意图。定义包装函数有什么问题:
def fetchem(cursor):(newline, indent)cursor.execute("SELECT * FROM webdata")(newline, indent)for item in cursor.fetchall():(newline, indent)print(item) -
Python 问题:
mydb和mycursor如果get_info最终被销毁? -
你的建议是我想处理的。然而,问题是我自己做不到。如果您以更清晰的方式提供相同的答案,我可能会按照您的指示@wallyk。
-
@asmitu:我已将我的评论合并到下面的答案中。
标签: python mysql python-3.x web-scraping