大家好我试图在使用python从网站抓取它们之后将一些值插入到MySQL数据库中。但是在将它们插入数据库时会给我错误。 错误如下:mysql.connector.errors.ProgrammingError:1064(42000):您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第2行的''附近使用正确的语法
请帮帮我。提前致谢。以下是代码:
conn = mysql.connector.connect(user='root',password='root',host='localhost',database ='crawler_database')
mycursor = conn.cursor()
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
my_list=[]
# GATHER INFORMATION FROM PAGE
for product_name in soup.findAll('span', {'itemprop': 'name'}):
prod_name = " " + product_name.string
my_list.append(prod_name)
print("Product Name :" + prod_name)
for low_price in soup.findAll('span', {'itemprop': 'lowPrice'}):
l_price = " " + low_price.string
my_list.append(l_price)
print("Lowest price :" + low_price.string)
for high_price in soup.findAll('span', {'itemprop': 'highPrice'}):
h_price = " " + high_price.string
my_list.append(h_price)
print("Highest price :" + high_price.string)
# FORMAT AND REMOVE UNWANTED CHARACTER FROM DATA
for specs in soup.findAll('ul', {'class': 'c-spec'}):
crop_str1 = str(specs).replace("<li>", "")
crop_str2 = crop_str1.replace("</li>", ",")
crop_str3 = crop_str2.replace("</ul>", "%")
crop_str4 = crop_str3.replace('<ul class="c-spec">', '$')
crop_str5 = crop_str4.partition('$')[-1].rpartition('%')[0]
my_list2 = crop_str5.split(",")
merged_list=my_list+my_list2
print(merged_list)
d0=" " + str(merged_list[0])
d1=" " + str(merged_list[1])
d2=" " + str(merged_list[2])
d3=" " + str(merged_list[3])
d4=" " + str(merged_list[4])
d5=" " + str(merged_list[5])
d6=" " + str(merged_list[6])
print("Android OS :" + merged_list[3])
print("Camera :" + merged_list[4])
print("SIM :" + merged_list[5])
print("Display size :" + merged_list[6])
mycursor.execute("""INSERT INTO mobile_spec(prod_name, low_price, high_price, android_os, camera, sim, d_size)
VALUES ((%s, %s, %s, %s, %s, %s , %s)""",(d0, d1, d2, d3, d4, d5, d6))
conn.commit()
答案 0 :(得分:2)
您将实际字符串&#34; d0&#34;等传递给MySQL,后者不知道如何处理它们。这些是Python变量,因此您需要将它们的值传递给MySQL。你用占位符来做到这一点:
mycursor.execute("""INSERT INTO mobile_spec(android_os, camera, sim, d_size)
VALUES (%s, %s, %s , %s)""", (d0, d1, d2, d3))
您的代码可以进一步简化,因为您首先在列表中获取了params,因此您可以直接将其传递给MySQL而不需要d*
个变量。
mycursor.execute("""INSERT INTO mobile_spec(android_os, camera, sim, d_size)
VALUES (%s, %s, %s , %s)""", my_list)