Kamikaze_goldfish
Kamikaze_goldfish

Reputation: 861

Scrapy trying to scrape business names href in python

I am trying to scrape the href for each business in yellowpages. I am very new to using scrapy and on my second day. I am using requests to get the actual url to search with the spider. What am I doing wrong with my code? I want to eventually have scrapy go to each business and scrape its address and other information.

# -*- coding: utf-8 -*-
import scrapy
import requests

search = "Plumbers"
location = "Hammond, LA"
url = "https://www.yellowpages.com/search"
q = {'search_terms': search, 'geo_location_terms': location}
page = requests.get(url, params=q)
page = page.url

class YellowpagesSpider(scrapy.Spider):
    name = 'quotes'
    allowed_domains = ['yellowpages.com']
    start_urls = [page]

    def parse(self, response):
        self.log("I just visited: " + response.url)
        items = response.css('span.text::text')
        for items in items:
            print(items)

Upvotes: 1

Views: 130

Answers (1)

Thomas Strub
Thomas Strub

Reputation: 1285

To get the name use:

response.css('a[class=business-name]::text')

To get the href use:

response.css('a[class=business-name]::attr(href)')

In the final call this looks like:

    for bas in response.css('a[class=business-name]'):
        item = { 'name' : bas.css('a[class=business-name]::text').extract_first(),
                  'url' : bas.css('a[class=business-name]::attr(href)').extract_first() }
        yield item

Result:

2018-09-13 04:12:49 [quotes] DEBUG: I just visited: https://www.yellowpages.com/search?search_terms=Plumbers&geo_location_terms=Hammond%2C+LA
2018-09-13 04:12:49 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.yellowpages.com/search?search_terms=Plumbers&geo_location_terms=Hammond%2C+LA>
{'name': 'Roto-Rooter Plumbing & Water Cleanup', 'url': '/new-orleans-la/mip/roto-rooter-plumbing-water-cleanup-21804163?lid=149760174'}
2018-09-13 04:12:49 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.yellowpages.com/search?search_terms=Plumbers&geo_location_terms=Hammond%2C+LA>
{'name': "AJ's Plumbing And Heating Inc", 'url': '/new-orleans-la/mip/ajs-plumbing-and-heating-inc-16078566?lid=1001789407686'}
...

Upvotes: 2

Related Questions