-
Notifications
You must be signed in to change notification settings - Fork 3
/
google-scrapper_2.0.py
183 lines (153 loc) · 6.33 KB
/
google-scrapper_2.0.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# -*- coding: utf-8 -*-
import requests
import time
import urllib
import argparse
import json
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from pathlib import Path
from lxml.html import fromstring
import os
import sys
from fake_useragent import UserAgent
'''
Commandline based Google Image scrapping. Gets up to 800 images.
Author: Rushil Srivastava ([email protected])
'''
def search(url):
# Create a browser and resize for exact pinpoints
browser = webdriver.Chrome()
browser.set_window_size(1024, 768)
print("\n===============================================\n")
print("[%] Successfully launched Chrome Browser")
# Open the link
browser.get(url)
time.sleep(1)
print("[%] Successfully opened link.")
element = browser.find_element_by_tag_name("body")
print("[%] Scrolling down.")
# Scroll down
for i in range(50):
element.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2) # bot id protection
browser.find_element_by_id("smb").click()
print("[%] Successfully clicked 'Show More Button'.")
for i in range(50):
element.send_keys(Keys.PAGE_DOWN)
time.sleep(0.3) # bot id protection
time.sleep(1)
print("[%] Reached end of Page.")
# Get page source and close the browser
source = browser.page_source
f = open('dataset/logs/google/source.html', 'w+', encoding='utf-8')
print('SOURCE')
f.write(source)
browser.close()
print("[%] Closed Browser.")
return source
def error(link):
print("[!] Skipping {}. Can't download or no metadata.\n".format(link))
file = Path("dataset/logs/google/errors.log".format(query))
if file.is_file():
with open("dataset/logs/google/errors.log".format(query), "a") as myfile:
myfile.write(link + "\n")
else:
with open("dataset/logs/google/errors.log".format(query), "w+") as myfile:
myfile.write(link + "\n")
def download_image(link, image_data):
# Use a random user agent header for bot id
ua = UserAgent()
headers = {"User-Agent": ua.random}
# Get the image link
try:
# Get the file name and type
file_name = link.split("/")[-1]
type = file_name.split(".")[-1]
type = (type[:3]) if len(type) > 3 else type
if type.lower() == "jpe":
type = "jpeg"
if type.lower() not in ["jpeg", "jfif", "exif", "tiff", "gif", "bmp", "png", "webp", "jpg"]:
type = "jpg"
#Download png and jpg image
if type == "png" :
download_image.delta += 1
# Download the image
print("[%] Downloading Image #{} from {}".format(download_image.delta, link))
try:
urllib.request.urlretrieve(link,
"dataset/google/{}/".format(query) + query +"_{}.{}".format(str(download_image.delta),
type))
print("[%] Downloaded File\n")
#with open("dataset/google/{}/{}_{}.json".format(query, query, str(download_image.delta)), "w") as outfile:
#json.dump(image_data, outfile, indent=4)
except Exception as e:
download_image.delta -= 1
print("[!] Issue Downloading: {}\n[!] Error: {}".format(link, e))
error(link)
except Exception as e:
download_image.delta -= 1
print("[!] Issue getting: {}\n[!] Error:: {}".format(link, e))
error(link)
if __name__ == "__main__":
# parse command line options
parser = argparse.ArgumentParser()
# parser.add_argument("url", help="Give the url that I should parse.")
parser.add_argument("keyword", help="Query I should parse.")
args = parser.parse_args()
# check directory and create if necessary
if not os.path.isdir("dataset/"):
os.makedirs("dataset/")
if not os.path.isdir("dataset/google/{}".format(args.keyword)):
os.makedirs("dataset/google/{}".format(args.keyword))
if not os.path.isdir("dataset/logs/google/".format(args.keyword)):
os.makedirs("dataset/logs/google/".format(args.keyword))
# set stack limit
sys.setrecursionlimit(1000000)
# get user input and search on google
query = args.keyword
query2 = query.replace('_','+')
url = "https://www.google.fr/search?q="+query2+"&dcr=0&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjJ482eroTZAhXNLVAKHYpbAs8Q_AUICigB&biw=766&bih=284"
source = search(url)
# Parse the page source and download pics
soup = BeautifulSoup(str(source), "html.parser")
ua = UserAgent()
headers = {"User-Agent": ua.random}
try:
os.remove("dataset/logs/google/errors.log")
except OSError:
pass
# Get the links and image data
links = soup.find_all("a", class_="rg_l")
print("[%] Indexed {} Images.".format(len(links)))
print("\n===============================================\n")
print("[%] Getting Image Information.\n")
images = {}
linkcounter = 0
for a in soup.find_all("div", class_="rg_meta"):
r = requests.get("https://www.google.com" + links[linkcounter].get("href"), headers=headers)
title = str(fromstring(r.content).findtext(".//title"))
link = title.split(" ")[-1]
print("\n[%] Getting info on: {}".format(link))
try:
image_data = "google", query, json.loads(a.text)["pt"], json.loads(a.text)["s"], json.loads(a.text)["st"], json.loads(a.text)["ou"], json.loads(a.text)["ru"]
images[link] = image_data
except Exception as e:
images[link] = image_data
print("[!] Issue getting data: {}\n[!] Error: {}".format(image_data, e))
linkcounter += 1
# Open i processes to download
download_image.delta = 0
for i, (link) in enumerate(links):
r = requests.get("https://www.google.com" + link.get("href"), headers=headers)
title = str(fromstring(r.content).findtext(".//title"))
link = title.split(" ")[-1]
if download_image.delta>=100:
break
try:
download_image(link, images[link])
except Exception as e:
error(link)
print("[%] Done. Downloaded {} images.".format(download_image.delta))
print("\n===============================================\n")