示例#1
0
def getsrctar(url):
    tmp = 'tmp.tar.gz'
    geturl(url, tmp)
    tar = tarfile.open(tmp)
    tar.extractall()
    tar.close()
    os.remove(tmp)
示例#2
0
def getexe(url, name):
    gzname = name + ".gz"
    geturl(url, gzname)
    with gzip.open(gzname, 'rb') as gz_in:
        with open(name, 'wb') as f_out:
            shutil.copyfileobj(gz_in, f_out)
    gz_in.close()
    f_out.close()
    os.remove(gzname)
def extractRealSupportedURI(uri):
    """
        Returns "real" URI if it survives redirects and returns a 200.

        Returns None otherwise.
    """

    realURI = None

    try:
        # this function follows the URI, resolving all redirects,
        # and detects redirect loops
        # iri2uri is needed for IRIs
        request = urllib.request.urlopen(httplib2.iri2uri(uri))
        
        if request.getcode() == 200:
            realURI = request.geturl()

    except urllib.error.HTTPError as e:
        # something went wrong, we don't care what
        realURI = None

    except urllib.error.URLError as e:
        # something went wrong, we don't care what
        realURI = None

    except UnicodeError as e:
        # something went very wrong with the IRI decoding
        realURI = None

    return realURI
示例#4
0
def get_photo(place_id):
    base_url = 'https://maps.googleapis.com/maps/api/place/details/json?'
    api_key = os.environ.get('GOOGLE_API_KEY')
    places_url = base_url + 'key=' + api_key + '&place_id=' + place_id
    request = urllib.request.urlopen(places_url)
    data = json.load(request)
    # to have random picture rather than first one
    number_of_photos = len(data['result']['photos'])
    selected_photo = randint(0, number_of_photos - 1)
    # would put selected photo instead of 0 below
    photo_reference = data['result']['photos'][0]['photo_reference']
    photo_base_url = 'https://maps.googleapis.com/maps/api/place/photo?'
    photo_url = photo_base_url + 'key=' + api_key + '&photoreference=' + photo_reference + '&maxwidth=300'
    request = urllib.request.urlopen(photo_url)
    print(request.geturl())
    return {"photo_url": request.geturl()}
示例#5
0
文件: skeleton.py 项目: ddanier/b5
    def __is_public_repository(self, url):
        request = urllib.request.urlopen(url)
        request_url = request.geturl()

        if url == request_url or url.rsplit('.', 1)[0] == request_url:
            try:
                if request.getcode() == 200:
                    return True
            except URLError:
                pass
        return False
示例#6
0
    def direct_download(self, image_url, path):
        """download data from url and save to path
            & optionally check if img downloaded is imgur dne file
        """
        def are_files_equal(file1, file2):
            """given two file objects, check to see if their bytes are equal"""
            return True if bytearray(file1.read()) == bytearray(
                file2.read()) else False

        dl, skp = 0, 0
        if os.path.isfile(path):
            raise FileExistsException("%s already exists." %
                                      os.path.basename(path))
        else:
            try:
                request = urllib.request.urlopen(image_url)
                redirect_url = request.geturl()

                # check if image did not exist and url got redirected
                if image_url != redirect_url:
                    self.log.debug("url, redirected_url = %s, %s" %
                                   (image_url, redirect_url))
                    if redirect_url == "http://imgur.com/":
                        raise HTTPError(
                            404,
                            "Image redirected to non-image link",
                            redirect_url,
                            None,
                            None,
                        )

                # check if image is imgur dne image before we download anything
                if self.delete_dne:
                    try:
                        with open(self.dne_path, "rb") as dne_file:
                            if are_files_equal(request, dne_file):
                                if self.debug:
                                    print("[ImgurDownloader] DNE: %s" %
                                          path.split("/")[-1])
                                return 0, 1
                    except (FileNotFoundError, OSError):
                        if self.debug:
                            print("[ImgurDownloader] Warning: DNE image not "
                                  "found at {}".format(self.dne_path))

                # proceed with downloading
                urllib.request.urlretrieve(image_url, path)
                dl = 1
            except (HTTPError, FileExistsError):
                skp = 1
        return dl, skp
示例#7
0
def process_download_list(cache, download_dir, input_list, options):
    """ Process the list of waiting downloads. """
    # Open cache to check if file has been downloaded
    if not os.path.exists(cache):
        if not options.cache_ignore:
            logging.error("Can't find cache directory")
            return
        else:
            logging.debug(
            "No cache file was found, but caching was ignored anyway"
            )

    # Open cache file and start downloading
    with open(cache, 'a+') as cache_file_handle:
        # Split the file by lines to get rid of whitespace
        cached_files = cache_file_handle.read().splitlines()
        for title in input_list:
            filename = title + ".torrent"
            http_url = input_list[title]
            logging.debug("Processing: " + http_url)
            logging.debug("Filename resolved to: " + filename)
            if len(filename) < 1:
                logging.critical("I was not able to find you a filename!\
                The file cannot be saved!")
                continue

            if (filename in cached_files) and not options.cache_ignore:
                logging.debug("File already downloaded: " + filename)
                continue
            if options.no_downloads:
                continue

            logging.info("Start downloading: " + filename)
            try:
                request = urllib.request.urlopen(http_url)
            except urllib.error.HTTPError as exception:
                msg = "HTTP Error: " + exception.code + " Line:" + http_url
                logging.info(msg)

            if request.geturl() != http_url:
                logging.info("URL Redirect - Not allowed to download")
                continue

            with open(os.path.join(download_dir, filename), 'w') as local_file:
                local_file.write(request.read())

            logging.info("Download successful: " + filename)

            # Cache the downloaded file so it doesn't get downloaded again
            cache_file_handle.writelines(filename + "\n")
示例#8
0
def get_valid_import_links(url):
    """
    Open the given URL, parse the HTML and return a list of valid links where
    the link file has a .aiida extension.
    """
    request = urllib.request.urlopen(url)
    parser = HTMLGetLinksParser(filter_extension='aiida')
    parser.feed(request.read().decode('utf8'))

    return_urls = []

    for link in parser.get_links():
        return_urls.append(urllib.parse.urljoin(request.geturl(), link))

    return return_urls
示例#9
0
def make_http_request_urllib(logger, url, method):
    url = _prepare_url_before_http_request(logger, url, method)

    req = urllib.request.Request(url,
                                 data=None,
                                 headers={'User-Agent': get_user_agent()},
                                 method=method)

    logger.debug("urllib.request.urlopen ({}) method={}".format(url, method))
    try:
        with urllib.request.urlopen(
                req,
                context=TRequestPolicy.SSL_CONTEXT,
                timeout=TRequestPolicy.HTTP_TIMEOUT) as request:
            data = '' if method == "HEAD" else request.read()
            headers = request.info()
            TRequestPolicy.register_successful_request()
            return request.geturl(), headers, data
    except UnicodeError as exp:
        raise RobotHttpException(
            "cannot redirect to cyrillic web domains or some unicode error",
            url, 520, method)
    except (ConnectionError, http.client.HTTPException) as exp:
        raise RobotHttpException(str(exp), url, 520, method)
    except socket.timeout as exp:
        logger.error("socket timeout, while getting {}: {}".format(url, exp))
        raise RobotHttpException("socket.timeout", url, 504, method)
    except urllib.error.URLError as exp:
        code = -1
        if hasattr(exp, 'code'):
            code = exp.code

        raise RobotHttpException("{} extype:{}".format(str(exp), type(exp)),
                                 url, code, method)  #
    except urllib.error.HTTPError as e:
        if e.code == 503:
            TRequestPolicy.deal_with_http_code_503(logger)
        if e.code == 405 and method == "HEAD":
            return make_http_request_urllib(logger, url, "GET")
        raise RobotHttpException("{} extype:{}".format(str(e), type(e)), url,
                                 e.code, method)
示例#10
0
normlen = len(start)
print(normlen)
for i in range(1,13):
    quer = '%20order%20by%20'+str(i)+'--+'
    #print(quer)
    parse = urlparse(req)
    qur = parse.query+quer
    #print(qur,type(qur))
    #print(req,type(req))
    parse = parse._replace(query=qur)
    #print(parse)
    url = urlunparse(parse)
    #print(url)
    request = urllib.request.urlopen(url)
    #print(request.info())
    print(request.geturl())
    html_len = len(request.read())
    print(html_len)
    if html_len < normlen:
        id = i
        print(i-1)
        break
    print('*'*10)
    
quer = ['%20UNION%20SELECT%201']
for i in range(2,id):
    quer.append(str(i))
union1 = ','.join(quer)
union = union1+'--+'
print(union)
parse = urlparse(req)
示例#11
0
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# Filename: ex2_get_a_webpage.py
# History: July 3,2018 - [Dan Chen] created
# This file is written for a very simple method to get a website page from the url.

from urllib import request,error


url = "http://www.baidu.com"
try:
    request = request.urlopen(url)
    print("geturl: ", request.geturl())
    result = request.read().decode("utf-8")
    print(result)
except error.URLError as e:
    if hasattr(e, 'code'):
        print("HTTPError")
        print("status code is ",e.code)
    elif hasattr(e,'reason'):
        print("URLError")
        print("reason is ", e.reason)

示例#12
0
文件: hython.py 项目: jepiroupo/PI
	def inicio(self, hdnTxtPesquisa=None):
	
		def numeroImagem():
			arq = open('c:/py/pi4/conf_imagem.txt', 'r')
			numero = arq.read()
			arq.close()
			arq = open('c:/py/pi4/conf_imagem.txt', 'w')
			arq.write(str(int(numero) + 1))
			arq.close()
			return numero
			
		# Organiza em ordem alfabetica e retira links duplicados
		def trataArray(seq):
			seq.sort()
			noDupes = []
			[noDupes.append(i) for i in seq if not noDupes.count(i)]
			return noDupes

		# Adiciona um texto em um arquivo
		def escreveArq(caminho, texto, modo):
			try:
				arq = open(caminho, modo, encoding='latin1')
				arq.write(texto)
				arq.close()
				return True
			except:
				return False

		# Faz a leitura do arquivo de configuracao das categorias		
		def leituraConf(conf):
			arq = open(conf,"r", encoding='latin1')
			categorias = []
			contador = 0
			while True:
				line = arq.readline()
				if not line:
					break
				else:
					if(line != ''):
						if line[:1] == '@':
							categorias.append([line[1:].strip().upper(), 0, [], []])
							contador += 1
						else:
							categorias[contador - 1][2].append(line.strip().lower())
			#Nome da categoria / Quantidade de palavras chaves / Lista de palavras / Lista de links
			return categorias
			
		def leituraHtmlBase(html_base):
			html = ""
			arq = open(html_base,"r", encoding='latin1')
			while True:
				line = arq.readline()
				if not line:
					break
				else:
					if(line != ''):
						html += line
			return html

		#Extrai a extensao do arquivo passado, se nao for um arquivo, ate primeiro ponto encontrado de tras para frente
		def extraiExtensao(texto):
			extensao = ""
			aux = ""
			contador = 1
			while contador <= len(texto):
				aux = texto[len(texto) - contador]
				if aux != ".":
					extensao = str(aux) + str(extensao)
					contador = contador + 1
				else:
					break
			return extensao
			
		def trataUrlLink(url, link):
			final = ""
			if link:
				link = link.strip()
				url = url.strip()
				if link != "#":
					if link[:7] != "http://" and link[:8] != "https://":
						if url[-4:] == ".php" or url[-5:] == ".html" or url[-4:] == ".htm" or url[-4:] == ".asp" or url[-4:] == ".jsp":
							aux = ""
							contador = 1
							while contador <= len(url):
								aux = url[len(url) - contador]
								if aux == "/":
									if link[:1] != "/":
										final += url[:(1-contador)] + link
									else:
										final += url[:(1-contador)] + link[1:]
									break
								else:
									contador = contador + 1
						else:
							final = url
							if final[-1:] == "/":
								if link[:1] != "/":
									final += link
								else:
									final += link[1:]
							else:
								if link[:1] != "/":
									final += "/" + link
								else:
									final += link
					else:
						final = link
			return final
			
		def categorizarPagina(soup, lista_categorias):
			meta_keywords_encontrado = False
			keywords = ""
			
			quantidade_1 = 0
			quantidade_2 = 0
			quantidade_3 = 0
			retorno = []
			retorno.append("") #Tipo de categorizacao
			retorno.append(0)  #Quantidade de palavras-chaves encontradas (principal)
			retorno.append("") #Categoria definida (principal)
			retorno.append(0)  #Quantidade de palavras-chaves encontradas (secundaria)
			retorno.append("") #Categoria definida (secundaria)
			retorno.append(0)  #Quantidade de palavras-chaves encontradas (terciaria)
			retorno.append("") #Categoria definida (terciaria)
			
			retorno.append(0)  #Quantidade de palavras mais encontrada (1)
			retorno.append("") #Palavra mais encontrada (1)
			retorno.append(0)  #Quantidade de palavras mais encontrada (2)
			retorno.append("") #Palavra mais encontrada (2)
			retorno.append(0)  #Quantidade de palavras mais encontrada (3)
			retorno.append("") #Palavra mais encontrada (3)
			
			for metas in soup.find_all('meta'):
				meta = metas.get('name')
				if meta == "keywords":
					meta_keywords_encontrado = True
					keywords = metas.get('content')
					retorno[0] = "Meta Tags"
					break
			
			if retorno[0] == "":
				retorno[0] = "Palavras-chaves"
				
			for categoria in lista_categorias:
				for palavras_chaves in categoria[2]:
					quant = 0
					
					if meta_keywords_encontrado == True:
						quant = keywords.count(palavras_chaves)
					else:
						quant = texto_html.count(palavras_chaves)
					categoria[1] += quant
				
					if quant > retorno[7]:
						if retorno[9] >= retorno[11]:
							retorno[11] = retorno[9]
							retorno[12] = retorno[10]
						if retorno[7] >= retorno[9]:
							retorno[9] = retorno[7]
							retorno[10] = retorno[8]
						retorno[7]  = quant
						retorno[8] = palavras_chaves
					elif meta_keywords_encontrado == True:
						if keywords.count(palavras_chaves) > retorno[9]:
							if retorno[9] >= retorno[11]:
								retorno[11] = retorno[9]
								retorno[12] = retorno[10]
							retorno[9]  = quant
							retorno[10] = palavras_chaves
						elif keywords.count(palavras_chaves) > retorno[11]:
							retorno[11]  = quant
							retorno[12] = palavras_chaves
					else:
						if texto_html.count(palavras_chaves) > retorno[9]:
							if retorno[9] >= retorno[11]:
								retorno[11] = retorno[9]
								retorno[12] = retorno[10]
							retorno[9]  = quant
							retorno[10] = palavras_chaves
						elif texto_html.count(palavras_chaves) > retorno[11]:
							retorno[11]  = quant
							retorno[12] = palavras_chaves
				
				#Verifica se ha outra categoria anterior com uma quantidade maior de palavras chaves encontradas
				if categoria[1] > quantidade_1:
					if retorno[3] >= retorno[5]:
						retorno[5] = retorno[3]
						retorno[6] = retorno[4]
					if retorno[1] >= retorno[3]:
						retorno[3] = retorno[1]
						retorno[4] = retorno[2]
					retorno[1]  = categoria[1]
					retorno[2] = categoria[0]
				elif categoria[1] > quantidade_2:
					if retorno[3] >= retorno[5]:
						retorno[5] = retorno[3]
						retorno[6] = retorno[4]
					retorno[3]  = categoria[1]
					retorno[4] = categoria[0]
				elif categoria[1] > quantidade_3:
					retorno[5]  = categoria[1]
					retorno[6] = categoria[0]
					
			return retorno
			
		def classificaLink(links, dominio, url, lista_categorias):
			validado = False
			link_interno = False
			link_retorno = ""
			categoria = ''
			# Obtem o "href" dos links
			link = links.get('href')
			# Verifica se o valor de link e nulo
			if link is not None:
				# Retira os espacos em branco antes e depois do link
				link = link.strip()
				if link.count(dominio) > 0:
					if link[:7] == "http://" or link[:8] == "https://":
						if link.find(dominio) < 15:
							link_interno = True
							link_retorno = link
							#link_site.append(link)
						else:
							link_retorno = link
							#link_externo.append(link)
					else:
						aux = trataUrlLink(url, link)
						#Verifica se com a URL, e possivel chegar a um caminho acessivel
						try:
							urllib.request.urlopen(aux)
							request = urllib.request.urlopen(link_retorno)
							html = request.read()
							html = html.decode("utf-8", "ignore")
							#Aplica o BeautifulSoup 4 no HTML
							soup = BeautifulSoup(html)
							categoria = categorizarPagina(soup, lista_categorias)
							validado = True
						#Caso nao seja possivel, utiliza o dominio para montar a URL
						except:
							aux = trataUrlLink("http://" + dominio, link)
						if aux != "":
							link_interno = True
							link_retorno = aux
							#link_site.append(aux)
				elif link.count(url) > 0:
					link_interno = True
					link_retorno = link
					#link_site.append(link)
				elif link[:7] == "http://" or link[:8] == "https://":
					link_retorno = link
					#link_externo.append(link)
				else:
					aux = trataUrlLink(url, link)
					#Verifica se com a URL, e possivel chegar a um caminho acessivel
					try:
						urllib.request.urlopen(aux)
						request = urllib.request.urlopen(link_retorno)
						html = request.read()
						html = html.decode("utf-8", "ignore")
						#Aplica o BeautifulSoup 4 no HTML
						soup = BeautifulSoup(html)
						categoria = categorizarPagina(soup, lista_categorias)
						validado = True
					#Caso nao seja possivel, utiliza o dominio para montar a URL
					except:
						aux = trataUrlLink("http://" + dominio, link)
					if aux != "":
						link_interno = True
						link_retorno = aux
						#link_site.append(aux)
			
			#Obtem a categoria do link
			if validado == False:
				try:
					request = urllib.request.urlopen(link_retorno)
					html = request.read()
					html = html.decode("utf-8", "ignore")
					#Aplica o BeautifulSoup 4 no HTML
					soup = BeautifulSoup(html)
					categoria = categorizarPagina(soup, lista_categorias)
					validado = True
				except:
					return ['']
			
			retorno = []
			retorno.append(link_retorno)
			retorno.append(link_interno)
			retorno.append(categoria[2])
			return retorno
			
		caminho_projeto = "c:/py/pi4/"
		caminho_projeto_fotos = caminho_projeto + "imagens_sites/"
		caminho_projeto_documentos = caminho_projeto + "documentos_sites/"
		caminho_aux_fotos = "imagens_sites/"
		caminho_aux_documentos = "documentos_sites/"
		pasta_site = ""
		
		diretorio_inicial = ""
		
		html = ""
		html_site = ""
		html_categoria = ""
		html_metodo = ""
		html_data_inicio = ""
		html_data_fim = ""
		html_link_internos = ""
		html_link_externos = ""
		html_palavras = ""

		texto_log_erros = ""
		texto_links = ""
			
		#URL do site
		url = hdnTxtPesquisa.strip()
		#Dominio extraido da URL do site (usado na classificacao de links)
		dominio = ""
		#Arquivo de erros
		arquivo_erros = 'log.txt'
		#Arquivo de links
		arquivo_links = 'links.txt'
		#Arquivo de conclusao
		arquivo_fim = 'fim.txt'
		#Arquivo contendo as categorias e palavras chaves
		arquivo_conf = caminho_projeto + 'crawler.conf'

		#Variavel que indica que o site possui meta tags com Keywords da pagina
		meta_keywords_encontrado = False	
		#Variavel que armazenara as keywords do site caso ele possua
		keywords = ""

		#Variavel que armazena a quantidade de palavras chaves encontradas
		quantidade_final = 0
		#O nome da categoria que teve mais palavras chaves presentes no html
		categoria_final = ""

		#Variavel que ira armazenar o HTML da pagina
		html = ""
		#Variavel que ira armazenar o texto do HTML da pagina
		texto_html = ""
		#Lista com os links internos encontrados no site
		link_site = []
		#Lista com os links externos encontrados no site
		link_externo = []
		#Lista com os caminhos de imagens
		caminhos_imagens = ""
		#Lista com os caminhos dos arquivos
		caminhos_arquivos = ""
		
		diretorio_inicial = url
		
		try:
			#Extrai todo o HTML da pagina
			request = urllib.request.urlopen(url)
			
			while url != request.geturl():
				url = request.geturl()
				request = urllib.request.urlopen(url)
			
			html = request.read()
			html = html.decode("utf-8", "ignore").lower()
		except:
			#RETORNO DE ERRO
			return "0"
		
		caminho_projeto = caminho_projeto + "sites/"
		
		#Encontra o dominio do site pela url digitada
		dominio = url.replace("http://www.", "").replace("https://www.", "").replace("/", "@").replace("http://", "").replace("https://", "")
		if dominio.find("@") != -1:
			dominio = dominio[:dominio.find("@")]
		
		#Aplica o BeautifulSoup 4 no HTML
		soup = BeautifulSoup(html)
		#Pega todo o texto da pagina
		texto_html = soup.get_text()
		
		pasta_site = diretorio_inicial.replace("http://", "").replace("/", "_") + "/"
	
		caminho_projeto = caminho_projeto + pasta_site
		arquivo_erros = caminho_projeto + arquivo_erros
		arquivo_links = caminho_projeto + arquivo_links
		
		if os.path.isfile(caminho_projeto + arquivo_fim):
			arq = open(caminho_projeto + arquivo_fim, 'r')
			retorno = arq.read()
			arq.close()
			#RETORNO CRAWLER JÁ FEITO
			return retorno
		
		lista_categorias = leituraConf(arquivo_conf)
		
		if not os.path.isdir(caminho_projeto):
			os.mkdir(caminho_projeto)

		html_site = url
		html_data_inicio = strftime("%d/%m/%Y %H:%M:%S")

		# ------ CATEGORIZAÇÃO DO SITE ------
		retorno = categorizarPagina(soup, lista_categorias)

		html_metodo = retorno[0]
		
		categoria_quant_1 = retorno[1]
		categoria_1 = retorno[2]
		categoria_quant_2 = retorno[3]
		categoria_2 = retorno[4]
		categoria_quant_3 = retorno[5]
		categoria_3 = retorno[6]
		
		if categoria_quant_1 > 0 and categoria_quant_2 > 0 and categoria_quant_3 > 0:
			categoria_quant_total = int(categoria_quant_1) + int(categoria_quant_2) + int(categoria_quant_3)
			
			perc_1 = int(categoria_quant_1) / int(categoria_quant_total) * 100
			perc_2 = int(categoria_quant_2) / int(categoria_quant_total) * 100
			perc_3 = int(categoria_quant_3) / int(categoria_quant_total) * 100
			
			palavra_quant_1 = retorno[7]
			palavra_1 = retorno[8]
			palavra_quant_2 = retorno[9]
			palavra_2 = retorno[10]
			palavra_quant_3 = retorno[11]
			palavra_3 = retorno[12]
			
			html_palavras = palavra_1 + " (" + str(palavra_quant_1) + " caso(s))"
			if palavra_quant_2 > 0:
				html_palavras = html_palavras + " - " + palavra_2 + " (" + str(palavra_quant_2) + " caso(s))"
			if palavra_quant_3 > 0:
				html_palavras = html_palavras + " - " + palavra_3 + " (" + str(palavra_quant_3) + " caso(s))"
			
			if categoria_1 == "":
				html_categoria = 'Nao foi possivel classificar o site em uma categoria'
			else:
				html_categoria = categoria_1 + "(" + str(perc_1) + "%)"
				
			if categoria_quant_2 > 0:
				html_categoria = html_categoria + " - " + categoria_2 + "(" + str(perc_2) + "%)"
			if categoria_quant_3 > 0:
				html_categoria = html_categoria + " - " + categoria_3 + "(" + str(perc_3) + "%)"
		else:
			html_categoria = 'Nao foi possivel classificar o site em uma categoria'
			html_palavras = 'Nao foi encontrado palavras-chaves'
		# -----------------------------------

		# ------ OBTENÇÃO DE LINKS ------
		contador = 1
		total_links = len(soup.find_all('a'))
		
		#Obtem todos os links do HTML
		for links in soup.find_all('a'):
			print("Link "+str(contador)+"/"+str(total_links))
			contador = contador + 1
			
			# ---- OBTENÇÃO DE DOCUMENTOS -----
			link = links.get('href')
			if link is not None:
				if link[-4:] == ".csv" or link[-4:] == ".pdf" or link[-4:] == ".doc" or link[-4:] == ".zip" or link[-4:] == ".rar" or link[-5:] == ".docx" or link[-4:] == ".xls" or link[-4:] == ".xlsx" or link[-3:] == ".7z":
					link = trataUrlLink("http://" + dominio, link)
					try:
						for cont in range(len(link) + 1):
							if link[-cont - 1] == "/":
								nome = link[-cont:]
								break
						local = caminho_projeto_documentos + nome
						urllib.request.urlretrieve(link, local)
						# Adiciona o documento na lista
						if caminhos_arquivos != "":
							caminhos_arquivos = caminhos_arquivos + "<#>"
						caminhos_arquivos = caminhos_arquivos + caminho_aux_documentos + nome + "<##>" + nome
					except:
						texto_log_erros += strftime("%d/%m/%Y %H:%M:%S") + " - Erro ao baixar arquivo: " + link + "\n"
				# ---------------------------------
				else:
					retorno = classificaLink(links, dominio, diretorio_inicial, lista_categorias)
					if retorno[0] != "":
						if retorno[1] == True:
							link_site.append(retorno[0] + "<#>" + retorno[2])
						else:
							link_externo.append(retorno[0] + "<#>" + retorno[2])
		# -------------------------------
		
		#Organiza a lista de links encontrados
		link_site = trataArray(link_site)
		link_externo = trataArray(link_externo)

		lista_links_internos = ""
		for link in link_site:
			if lista_links_internos != "":
				lista_links_internos = lista_links_internos + "<##>"
			lista_links_internos = lista_links_internos + link
			
		lista_links_externos = ""
		for link in link_externo:
			if lista_links_externos != "":
				lista_links_externos = lista_links_externos + "<##>"
			lista_links_externos = lista_links_externos + link
		
		# ------ OBTENÇÃO DE IMAGENS ------
		contador = 1
		total_imagens = len(soup.find_all('img'))
		for imagens in soup.find_all('img'):
			print("Imagem "+str(contador)+"/"+str(total_imagens))
			imagem = imagens.get('src')
			imagem = trataUrlLink("http://" + dominio, imagem)
			extensao = extraiExtensao(imagem)
			
			if extensao.count("jpg") == 0 and extensao.count("jpeg") == 0 and extensao.count("bmp") == 0 and extensao.count("gif") == 0 and extensao.count("png") == 0:
				texto_log_erros += strftime("%d/%m/%Y %H:%M:%S") + " - Extens\xe3o de imagem desconhecida: " + extensao + "\n"
				contador = contador + 1
				continue
			
			local = caminho_projeto_fotos + numeroImagem() + "." + extensao
			if imagem is not None:
				try:
					urllib.request.urlretrieve(imagem, local)
				except:
					texto_log_erros += strftime("%d/%m/%Y %H:%M:%S") + " - Erro ao baixar imagem: " + imagem + "\n"
					contador = contador + 1
					continue
				
				obj = os.stat(local)
				if obj.st_size < 1024:
					try:
						os.remove(local)
					except:
						texto_log_erros += strftime("%d/%m/%Y %H:%M:%S") + " - Erro ao remover imagem muito pequena: " + local + "\n"
				else:
					# Adiciona a imagem na lista
					if caminhos_imagens != "":
						caminhos_imagens = caminhos_imagens + "<#>"
						
					nome = ""
					for cont in range(len(local) + 1):
						if local[-cont - 1] == "/":
							nome = local[-cont:]
							break
					
					caminhos_imagens = caminhos_imagens + caminho_aux_fotos + nome
				contador = contador + 1
		# ---------------------------------
		
		html_data_fim = strftime("%d/%m/%Y %H:%M:%S")
		
		retorno = url + "|" + html_data_inicio + "|" + html_data_fim + "|" + html_metodo + "|" + html_categoria + "|" + lista_links_internos + "|" + lista_links_externos + "|" + caminhos_imagens + "|" + caminhos_arquivos + "|" + html_palavras
		
		arq = open(caminho_projeto + arquivo_fim, 'w')
		arq.write(retorno)
		arq.close()
		
		return retorno
示例#13
0
def main():
    try:
        from bs4 import BeautifulSoup
        import urllib.request
        import re
        import pyperclip
    except ImportError:
        print(
            "Some modules are not installed. Run \n python -m pip install -r requirements.txt"
        )
        exit()

    url_choice = input("IGG-Games Link: ")
    if not (url_choice.startswith("http://")
            or url_choice.startswith("https://")):
        url_choice = "http://" + url_choice
    req = urllib.request.Request(
        url_choice,
        data=None,
        headers={
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
        })

    try:
        request = urllib.request.urlopen(req)
    except urllib.error.URLError:
        print("URL could not be opened.")
        exit()

    soup = BeautifulSoup(request, "lxml")
    source_list = []

    # Iterate through all sources
    for source in soup.find_all("b"):
        source_list += re.findall(
            r"Link [0-9]*[a-zA-Z]+\.* *[0-9]*[a-zA-Z]+\.*[a-zA-Z]*",
            str(source))
        # Remove torrent link if available
        if str(source).__contains__("TORRENT"):
            source_list.pop(0)

    # Remove 'Link' text from source_list
    for count in range(len(source_list)):
        item = source_list[count]
        source_list[count] = item[5:]

    if not source_list:
        print("No Link sources found.")
        exit()
    for counter, value in enumerate(source_list):
        print(str(counter + 1) + ") " + value)
    source_choice = input("Choose download source: ")
    while not isinstance(source_choice, int):
        try:
            source_choice = int(source_choice)
            if source_choice > len(source_list):
                raise ValueError
        except ValueError:
            source_choice = input("Please enter a number between 1 and " +
                                  str(len(source_list)) + ": ")

    finalOutput = ""
    for paragraph in soup.find_all("p"):
        if source_list[source_choice - 1] in paragraph.text:
            print("\n")
            for hyperlink in paragraph("a"):
                string = hyperlink.get('href')
                # Check if button is already redirecting to direct link
                if "http://bluemediafiles.com" not in string:
                    sec_req = urllib.request.Request(
                        string,
                        data=None,
                        headers={
                            'User-Agent':
                            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
                        })
                    try:
                        request = urllib.request.urlopen(sec_req)
                    except urllib.error.URLError:
                        print("URL could not be opened.")
                        exit()
                    print(request.geturl())
                    finalOutput += request.geturl() + "\n"
                else:
                    sec_req = urllib.request.Request(
                        string,
                        data=None,
                        headers={
                            'User-Agent':
                            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
                        })
                    try:
                        request = urllib.request.urlopen(sec_req)
                    except urllib.error.URLError:
                        print("URL could not be opened.")
                        exit()

                    soup = BeautifulSoup(request, "lxml")

                    for script in soup.find_all("script"):
                        matches = re.findall(
                            r"Goroi_n_Create_Button\(\"(.*?)\"\)", str(script))
                        if len(matches) > 0:
                            string = 'https://bluemediafiles.com/get-url.php?url=' + _bluemediafiles_decodeKey(
                                matches[0])
                            third_req = urllib.request.Request(
                                string,
                                data=None,
                                headers={
                                    'User-Agent':
                                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
                                })
                            try:
                                request = urllib.request.urlopen(third_req)
                            except urllib.error.URLError:
                                print("URL could not be opened.")
                                exit()
                            print(request.geturl())
                            finalOutput += request.geturl() + "\n"

            print("\n")
            if input("Copy to Clipboard? y/n ").lower() == "y":
                pyperclip.copy(finalOutput)
示例#14
0
    def make_http_request_urllib(url, method, timeout):
        assert THttpRequester.logger is not None
        assert method in {"GET", "HEAD"}

        if not url.lower().startswith('http'):
            raise THttpRequester.RobotHttpException(
                'unknown protocol, can be only http or https', url, 520,
                method)

        try:
            url = THttpRequester._prepare_url_before_http_request(url, method)

            req = urllib.request.Request(
                url,
                data=None,
                headers={'User-Agent': get_user_agent()},
                method=method)

            with urllib.request.urlopen(req,
                                        context=THttpRequester.SSL_CONTEXT,
                                        timeout=timeout) as request:
                headers = request.info()
                data = ''
                if method == 'GET':
                    file_extension = THttpRequester.get_file_extension_by_content_type(
                        headers)
                    if not is_video_or_audio_file_extension(
                            file_extension
                    ) or THttpRequester.ENABLE_VIDEO_AND_AUDIO:
                        data = request.read()
                THttpRequester.register_successful_request()
                return request.geturl(), headers, data
        except IndexError as exp:
            raise THttpRequester.RobotHttpException(
                "general IndexError inside urllib.request.urlopen", url, 520,
                method)
        except UnicodeError as exp:
            raise THttpRequester.RobotHttpException(
                "cannot redirect to cyrillic web domains or some unicode error",
                url, 520, method)
        except (ConnectionError, http.client.HTTPException) as exp:
            raise THttpRequester.RobotHttpException(str(exp), url, 520, method)
        except socket.timeout as exp:
            THttpRequester.logger.error(
                "socket timeout, while getting {}: {}".format(url, exp))
            raise THttpRequester.RobotHttpException("socket.timeout", url, 504,
                                                    method)
        except ssl.SSLError as exp:
            THttpRequester.logger.error(
                "ssl error, while getting {}: {}".format(url, exp))
            raise THttpRequester.RobotHttpException("ssl.SSLError", url, 504,
                                                    method)
        except urllib.error.URLError as exp:
            code = -1
            if hasattr(exp, 'code'):
                code = exp.code

            raise THttpRequester.RobotHttpException("{} extype:{}".format(
                str(exp), type(exp)), url, code, method)  #
        except urllib.error.HTTPError as e:
            if e.code == 503:
                THttpRequester.deal_with_http_code_503()
            if e.code == 405 and method == "HEAD":
                return THttpRequester.make_http_request_urllib(
                    url, "GET", timeout)
            raise THttpRequester.RobotHttpException(
                "{} extype:{}".format(str(e), type(e)), url, e.code, method)
示例#15
0
import numpy as np
import pandas as pd
import requests
import json
#import urllib
from urllib import request, parse

url = 'https://www.lfd.uci.edu/~gohlke/pythonlibs/'
url2 = url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'

#resp = request.urlopen(url)

headers = {
    'User-Agent':
    r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
    r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer':
    r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
    'Connection':
    'keep-alive'
}

req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
url22 = request.geturl()
print(url22)
#print(page)
示例#16
0
from urllib import request

if __name__ == "__main__":
    req = request.Request("https://www.bilibili.com/")
    request = request.urlopen(req)
    print("geturl打印信息:%s" % (request.geturl()))
    print('*******************************************')
    print("info打印信息:%s" % (request.info()))
    print('*****************************************')
    print("getcode打印信息:%s" % (request.getcode()))