0

I'm trying to write a dictionary into sql database, but without success giving me:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))
NameError: name 'url' is not defined

spider:

from scrapy.crawler import CrawlerProcess
import scrapy
import sqlite3

class Wellness(scrapy.Spider):
name = "wellness"
start_urls = ['https://www.wellness.com/dir/6022571/acupuncturist/ri/east-greenwich/hwasook-lee-phoenix-fertility-center-dac']

def parse(self, response):
    item = {
            'url' : response.request.url,
            'First_and_Last_Name' : response.css('h1::text').get(),
    }       
    directions_link = response.css('#directions_tab a::attr(href)').get()
    yield scrapy.Request(response.urljoin(directions_link), callback=self.parse_directions, meta={'item': item})

def parse_directions(self, response):
    item = response.meta['item']
    item['Phone'] = response.css('.tel::text').get()
    yield item

    db = sqlite3.connect('posts.db')
    db.execute('''CREATE TABLE IF NOT EXISTS posts(id INTEGER PRIMARY KEY AUTOINCREMENT,url TEXT, First_and_Last_Name TEXT);''') 
    db.commit()

    cursor = db.cursor()
    cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (url, First_and_Last_Name))

    db.commit()
    db.close()

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(Wellness)
    process.start()

What am I doing wrong here. Any and all help is appreciated. Thanks!

1
  • 2
    Your using url but where have u defined it ?? Commented May 30, 2020 at 15:44

1 Answer 1

1

You want to use item['url'] instead of url, same for First_and_Last_Name:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES("%s", "%s")' % (item['url'], item['First_and_Last_Name']))

Also, don't use string formatting with SQL statements, as it makes your code vulnerable to SQL injection attacks. Let the cursor.execute method do the escaping for you:

cursor.execute('INSERT INTO posts(url, First_and_Last_Name) VALUES(?, ?)', (item['url'], item['First_and_Last_Name']))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.