-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCLscrapergit.py
More file actions
55 lines (40 loc) · 1.82 KB
/
Copy pathCLscrapergit.py
File metadata and controls
55 lines (40 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- coding: utf-8 -*-
import scrapy
#cleans the text from the body of a listing. Returns a list of words.
def text_clean(text):
clean_text = []
for t in text:
t = (''.join(char for char in t if (char.isalnum() or char == ' '))).lower()
t = t.split(' ')
clean_text += t
return(clean_text)
#Searches for certain keywords and returns listings containing those words.
#Function needs to be modified to find keywords you're interested in.
def keyword_search(text):
if '' in text
return(True)
else:
return(False)
class HousingSpider(scrapy.Spider):
name = '' #Name of file
allowed_domains = ['#region.craigslist.org'] #Page for Craigslist region you're interested in.
start_urls = [''] #Page containing the listings you want to scrape.
def parse(self, response):
listings = response.xpath("//ul[@class='rows']/li")
for listing in listings:
link = listing.xpath(".//a/@href").get()
yield scrapy.Request(url=link, callback=self.parse_listing, meta={'link_url': link})
next_page_rel = response.xpath(".//a[@class='button next']/@href").getall()
next_page = f'https://ALLOWED_DOMAINS{next_page_rel[0]}' #navigates to next page of listings. ALLOWED_DOMAINS
#should be replaced with the domain from allowed_domains variable.
if next_page:
yield scrapy.Request(url = next_page, callback=self.parse)
def parse_listing(self, response):
link = response.request.meta['link_url']
time = response.xpath(".//p[@id='display-date']/time/@title").getall()
text = text_clean(response.xpath(".//section[@id='postingbody']/text()").getall())
if keyword_search(text) == True:
yield {
'time': time,
'link': link,
}